开发者

Swingworker producing duplicate output/output out of order?

What is the proper way to guarantee delivery when using a SwingWorker? I'm trying to route data from an InputStream to a JTextArea, and I'm running my SwingWorker with the execute method. I think I'm following the example here, but I'm getting out of order results, duplicates, and general nonsense.

Here is my non-working SwingWorker:

class InputStreamOutputWorker extends SwingWorker<List<String>,String> {

    private Inp开发者_开发百科utStream is;
    private JTextArea output;

    public InputStreamOutputWorker(InputStream is, JTextArea output) {
        this.is = is;
        this.output = output;
    }

    @Override
    protected List<String> doInBackground() throws Exception {
        byte[] data = new byte[4 * 1024];
        int len = 0;

        while ((len = is.read(data)) > 0) {
            String line = new String(data).trim();
            publish(line);
        }

        return null;
    }

    @Override
    protected void process( List<String> chunks )
    {
        for( String s : chunks )
        {
            output.append(s + "\n");
        }
    }
}


You need to use the 'len' value when creating your string:

String line = new String(data,0,len).trim();

Also, I would recommend you wrap your InputStream in a BufferedReader and use the 'readLine()' method:

BufferedReader reader = new BufferedReader(is);
...
String line = reader.readLine()


Clear your data array after reading from the input stream.

while ((len = is.read(data)) > 0) {
                String line = new String(data).trim();
                publish(line);
                Arrays.fill(data,(byte)0);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜