CBennett
CBennett

Reputation: 39

Socket file transferring not reading properly

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();
    }
}

Upvotes: 0

Views: 55

Answers (1)

Pyrce
Pyrce

Reputation: 8596

The reason the whole files goes into data[0] is because your whole file is less than socket.getReceiveBufferSize() and you do a single iteration of your while loop. To split by line instead, use a BufferedReader and call .readLine() in your while loop.

Something like this would do:

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

Note that you'll need to add try catches appropriately as well as any other logic you want.

Upvotes: 2

Related Questions