小编lda*_*dam的帖子

如何正确缓冲Java输入/输出/文件流?

我正在编写一个需要通过网络发送文件的应用程序.我到目前为止只学过如何使用标准的java.net和java.io类(在我大学的第一年),所以我没有java.nio和netty以及所有那些好东西的经验.我使用Socket和ServerSocket类以及BufferedInput/OutputStreams和BufferedFile流设置了一个正常工作的服务器/客户端,如下所示:

服务器:

    public class FiletestServer {

    static ServerSocket server;
    static BufferedInputStream in;
    static BufferedOutputStream out;

    public static void main(String[] args) throws Exception {
    server = new ServerSocket(12354);
    System.out.println("Waiting for client...");
    Socket s = server.accept();
    in = new BufferedInputStream(s.getInputStream(), 8192);
    out = new BufferedOutputStream(s.getOutputStream(), 8192);
    File f = new File("test.avi");
    BufferedInputStream fin = new BufferedInputStream(new FileInputStream(f), 8192);

    System.out.println("Sending to client...");
    byte[] b = new byte[8192];
    while (fin.read(b) != -1) {
        out.write(b);
    }
    fin.close();
    out.close();
    in.close();
    s.close();
    server.close();
    System.out.println("done!");
    }
}
Run Code Online (Sandbox Code Playgroud)

和客户: …

java file-io stream buffering

5
推荐指数
1
解决办法
4785
查看次数

Class.getResource(className)给我NullPointerException

我已经建立了一个独立于平台的库,我想在J2SE和Android项目中使用它.在这个库中,我有一个Version类从清单加载其版本详细信息.在PC上运行良好,在Android上我得到了一个NullPointerException,我无法弄清楚为什么.

这是我的班级:

public class Version {

    private static int APPCODE = 12354;
    private static int MAJOR;
    private static int MINOR;
    private static char RELEASE;
    private static int BUILD;
    private static int PROTOCOL;

    static {
        try {
            Class clazz = Version.class;
            String className = clazz.getSimpleName() + ".class";
            String classPath = clazz.getResource(className).toString(); //NullPointerException
            if (classPath.startsWith("jar")) {
                String manifestPath = classPath.substring(0,
                        classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
                Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                Attributes attr = manifest.getMainAttributes();
                //APPCODE = Integer.parseInt(attr.getValue("APPCODE")); …
Run Code Online (Sandbox Code Playgroud)

java android cross-platform nullpointerexception android-resources

5
推荐指数
1
解决办法
2001
查看次数

阻止用户一次按两个按钮?

有没有办法只注册一个按钮?在我的活动中,我有两个按钮,每个按钮开始另一个活动 - 此时如果我同时按下它们,两个活动都开始,一个在另一个上面.我想防止这种情况,并且在任何给定时间只运行一个或另一个.我想过要禁用多点触控,但这对我来说有些不好意思.

编辑:我试过这样做:

public class MainActivity extends Activity {

    Button btn_send;
    Button btn_receive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_receive = (Button) findViewById(R.id.btn_receive);
        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v.equals(btn_send)) {
                    if (isWifiConnected()) {
                        btn_receive.setClickable(false);
                        startActivity(new Intent(MainActivity.this,
                                SendActivity.class));
                    } else {
                        Toast.makeText(MainActivity.this,
                                "Wifi connection required", Toast.LENGTH_SHORT)
                                .show();
                    }
                } else if (v.equals(btn_receive)) {
                    if (isWifiConnected()) {
                        btn_send.setClickable(false);
                        startActivity(new Intent(MainActivity.this,
                                ReceiveActivity.class));
                    } else {
                        Toast.makeText(MainActivity.this,
                                "Wifi connection …
Run Code Online (Sandbox Code Playgroud)

user-interface android multi-touch

5
推荐指数
2
解决办法
2532
查看次数

TryGet 方法风格的最佳实践

我有一个枚举方法,如下所示:

public static TEnum GetEnumByStringValue<TEnum>(string value) where TEnum : struct, IConvertible, IComparable, IFormattable
{
  if(!typeof(TEnum).IsEnum)
  {
    throw new ArgumentException("TEnum must be an enumerated type.");
  }

  Type type = typeof(TEnum);
  FieldInfo[] fieldInfos = type.GetFields();
  foreach (FieldInfo fieldInfo in fieldInfos)
  {
    StringValue[] stringValues = fieldInfo.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
    if (stringValues != null)
    {
      foreach (StringValue stringValue in stringValues)
      {
        if (stringValue.Value.Equals(value))
        {
          return (TEnum)Enum.Parse(typeof(TEnum), fieldInfo.Name);
        }
      }
    }

  }
  throw new ArgumentOutOfRangeException("value", "Value was not found in enum's string values.");
}
Run Code Online (Sandbox Code Playgroud)

我想实现一个, …

c# methods exception

5
推荐指数
1
解决办法
6792
查看次数

如何将两个具有共同成员的类组合成一个输入?

我需要创建一个服务,它需要3个输入,这基本上归结为A,和我们将调用B的组合.ABC

假设这些类定义如下:

public abstract class InputBase
{
  public bool Option1 { get; set; }
  public decimal Rate { get; set; }
  public DateTime DateCreated { get; set; }
}

public class A : InputBase
{
  public decimal Fee { get; set; }
}

public class B : InputBase
{
  public decimal Fee { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

所述Fee以s AB是不同的和独立的,并且可以是不同的,对于像箱子C哪里可以做的组合AB在同一请求中在一起.

我们目前只有一个看起来像这样的类:

public class …
Run Code Online (Sandbox Code Playgroud)

.net c# inheritance composition

5
推荐指数
1
解决办法
83
查看次数

监视变量更改时暂停执行?

当监视变量(不是属性,只是普通变量)发生变化时,是否可以中断执行以查看更改发生的位置?我搜索并发现这个问题与看起来不像我正在寻找的属性有关.

此变量在几千行代码中多次使用,但仅null在问题发生时才更改.我们正试图追踪这个问题.

c# debugging visual-studio-2010

4
推荐指数
1
解决办法
4449
查看次数

如何从 puppeteer-sharp 中获取可读的浏览器/页面错误?

我正在使用 puppeteer-sharp 将一些页面呈现为 PDF。我想知道页面在运行时在浏览器中呈现时是否有任何问题,因此我设置了一些事件处理程序:

_page.Error += (sender, args) =>
{
    _logger.LogCritical(args.Error);
};

_page.PageError += (sender, args) =>
{
    _logger.LogError(args.Message);
};

_page.Console += (sender, args) =>
{
    switch (args.Message.Type)
    {
        case ConsoleType.Error:
            _logger.LogError(args.Message.Text);
            break;
        case ConsoleType.Warning:
            _logger.LogWarning(args.Message.Text);
            break;
        default:
            _logger.LogInformation(args.Message.Text);
            break;
    }
};
Run Code Online (Sandbox Code Playgroud)

当我在页面上收到错误时,args.Message.Text似乎只包含"ERROR JSHandle@error". 这不是很有帮助。

console.log在页面上测试正常并且记录正常,这似乎是错误的问题。

我需要做些什么才能从这些错误中获得一些可读的东西?

更新:我尝试访问args.Message.Args和使用JsonValueAsync()这些 args,但这似乎导致了一些异步异常,破坏了 devtools 协议,因为我开始收到超时错误,然后错误抱怨 Web 套接字被破坏。

看来这是 puppeteer 本身的问题:https : //github.com/GoogleChrome/puppeteer/issues/3397

c# error-handling puppeteer puppeteer-sharp

4
推荐指数
1
解决办法
1657
查看次数

在构造函数中初始化public static final变量

我正在尝试Version为我的应用程序创建一个类,它将在加载时从清单中读取版本号,然后仅参考例如Version.MAJOR我在其他地方需要它的地方.但是,我遇到了这样的问题.这是我目前的代码:

 public class Version {

    public static final int APPCODE;
    public static final int MAJOR;
    public static final int MINOR;
    public static final char RELEASE;
    public static final int BUILD;

    static {

        try {
            Class clazz = Version.class;
            String className = clazz.getSimpleName() + ".class";
            String classPath = clazz.getResource(className).toString();
            if (classPath.startsWith("jar")) {
                String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
                Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                Attributes attr = manifest.getMainAttributes();
                APPCODE = Integer.parseInt(attr.getValue("APPCODE"));
                MAJOR = Integer.parseInt(attr.getValue("MAJOR")); …
Run Code Online (Sandbox Code Playgroud)

java initialization constants manifest static-classes

3
推荐指数
1
解决办法
3787
查看次数

Horizo​​ntalAlignment =“ Stretch”在TreeViewItem中不起作用

这是一个不起作用的示例:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <TreeView HorizontalAlignment="Stretch">
        <TreeViewItem Header="Stuff" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1"></TextBox>

            </Grid>
        </TreeViewItem>
    </TreeView>
</Window>
Run Code Online (Sandbox Code Playgroud)

我希望文本框可以延伸到窗口的宽度,但是您会得到以下信息:

看起来像什么

运行时看起来像什么

键入时,文本框会扩展,这不是我想要的。

我现在正在考虑可以将第二列的宽度设置为的宽度,TreeViewItem但是我不确定该怎么做。

我试过将网格放在各种面板中,但这也不起作用。我还设置HorizontalAlignmentHorizontalContentAlignmentStretch对文本本身,但也不能正常工作。

这是Grid控件的一些限制吗?将文本框本身放在树状视图中将使其按我的意愿扩展,但是我需要在其旁边放置标签,如果有多个字段,则如果所有文本框都对齐,则看起来会更好。

更新

使用不同的ControlTemplate标题可以拉伸,但内容仍然不能拉伸。

<TreeView HorizontalAlignment="Stretch">
        <TreeViewItem Style="{DynamicResource StretchableTreeViewItemTemplate}" HorizontalAlignment="Stretch" Header="Stuff">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0">Some random text</Label>
                <TextBox Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>
            </Grid>
        </TreeViewItem>
    </TreeView> …
Run Code Online (Sandbox Code Playgroud)

.net c# wpf xaml

2
推荐指数
2
解决办法
3085
查看次数

进度条更新程序使用CPU

我想让用户了解I/O操作的进度.目前我有一个内部课程,在我启动I/O之前启动,并在完成后停止.它看起来像这样:

class ProgressUpdater implements Runnable {

        private Thread thread;
        private long last = 0;
        private boolean update = true;
        private long size;

        public ProgressUpdater(long size) {
            this.size = size;
            thread = new Thread(this);
        }

        @Override
        public void run() {
            while (update) {
                if (position > last) {
                    last = position;
                    double progress = (double) position / (double) size * 100d;
                    parent.setProgress((int) progress);
                }
            }
        }

        public void start() {
            thread.start();
        }

        public void stop() {
            update = false;
            parent.setProgress(100);
        } …
Run Code Online (Sandbox Code Playgroud)

java swing multithreading jprogressbar event-dispatch-thread

1
推荐指数
2
解决办法
1030
查看次数