0

When I receive the file, it adds the WHOLE file into the 0 index of 'data'. How do I make it so each line of the file being received goes into a new index, basically adding like I'm trying to do.

public Downloader(Socket socket) {
    List<String> data = new ArrayList<String>();
    try {
        InputStream input = socket.getInputStream();
        byte[] buffer = new byte[socket.getReceiveBufferSize()];
        int bytesReceived = 0;
        while ((bytesReceived = input.read(buffer)) > 0) {
            String line = new String(buffer, 0, bytesReceived);
            if (line.trim().length() > 0) {
                data.add(line);
            }
        }
        Data.rawData = data;
        input.close();
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

1 回答 1

2

整个文件进入的原因data[0]是因为您的整个文件小于socket.getReceiveBufferSize()并且您对 while 循环进行了一次迭代。要改为按行拆分,请在 while 循环中使用BufferedReaderand 调用。.readLine()

这样的事情会做:

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while (line = input.readLine()) != null) {
    data.add(line);
}

请注意,您需要适当地添加尝试捕获以及您想要的任何其他逻辑。

于 2013-03-29T01:37:24.233 回答