The following piece of code tries to introduce a newline character into a byte array and write the byte array to a file.
import java.io.*;
public class WriteBytes {
public static void main(String args[]) {
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c' };
FileOutputStream outfile = null;
try {
outfile = new FileOutputStream("newfile.txt");
outfile.write(cities);
outfile.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Contents of the newfile were: newyorkdc
What I expected was:
newyork
dc
I tried to typecast '\n'
to (byte)'\n'
but to no avail.
Solution: Change the array initialization to
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r','\n', 'd', 'c' };
I had used Notepad++ to view the contents of the file.I suppose it suppressed the newline character but accepted the carriage return followed by newline combination.