From the following code :
import java.io.*;
class fileTester {
public static void main( String args[]) throws IOException {
String string = "Suhail" + "\n" + "gupta";
FileOutputStream fos = new FileOutputStream( new File("break.txt"));
byte[] data = string.getBytes();
fos.write( data );
fos.close();
}
}
I expected the output to be :
Suhail
Gupta
int the file created (i.e both the strings in a new line ) but the output is in a single line. Suhail gupta
Why is it so when i have used \n character in between the 2 Strings ?
You shouldn’t hard-code the new line character when writing to a file. Use the OS-specific newline String instead:
Also, rather than use a FileOutputStream to write raw bytes to a text file, why not wrap it in a PrintStream object so you can easily just use println(…) to do your newlines for you?