Indigenuity
Indigenuity

Reputation: 9760

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.

Upvotes: 2

Views: 3236

Answers (3)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

This writes line by line to the file:

byte[] buff = "line1\nline2\nline3".getBytes();   
InputStream is = new ByteArrayInputStream(buff);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
File file = new File("C:\\folder", "outputFile.txt");
PrintStream ps = new PrintStream(file);
String line;
while((line = br.readLine()) != null) {
    ps.println(line);
}
br.close();
ps.close();

Finally, the content of outputFile.txt:

line1
line2
line3

Upvotes: 1

havexz
havexz

Reputation: 9590

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.

Upvotes: 2

Tudor
Tudor

Reputation: 62469

In Unix the newline is the character \n, while in Windows it is the pair \r\n. So you can consider looking through the buffer each time and inserting a \r in front of \n.

Upvotes: 1

Related Questions