Search code examples
javawindowslinuxcharacter-encodingnio

New line character lost in transfer from linux to windows


I wrote a simple client/server in java that transfers files using java NIO Socketchannel. When I transfer a simple text file from Linux to Windows, the line returns are all gone. I know the two operating systems use different character encodings, but I'm trying to figure out where in the process I would take that into account.

When the server sends the files, it just sends the raw bytes over, read in by a FileInputStream.

My client reads in the bytes from the channel to a ByteBuffer, then I get the byte array out of that.

socketChannel.read(this.readBuffer);

I loop through the array of bytes each time I receive more from the channel, looking for EOF, and if I don't find it, I put it into a file:

FileOutputStream fos = new FileOutputStream(filepath);
fos.write(data);  //data is my byte[]
fos.close();

I know this probably has an obvious solution to some, but I'm not too familiar with all the concepts involved.


Solution

  • Basic problem is that Linux has \n as newline and windows comprised of \r (carriage return)and \n (line feed).

    To get the system's line separator by:

    System.getProperty("line.separator");
    

    Now the question where you gonna put it. Now if you want to save the file at the client side with client side line separator then use the above api to the get the line separator and replace in the data.

    Since you have no idea on the client side what server is using (i m trying to go for generic soln) for line separate, try to replace both type of line separators with the client side line separators.