开发者

why the other part is not printed in the next line?

开发者 https://www.devze.com 2023-03-27 21:15 出处:网络
From the following code : import java.io.*; cla开发者_运维问答ss fileTester { public static void main( String args[]) throws IOException {

From the following code :

import java.io.*;

cla开发者_运维问答ss 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:

String newline = System.getProperty("line.separator");

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?


I guess you are using notepad to see the file.

End of line character varies from system to system. A more advanced text editor (v.g. Notepad++) will show it correctly, because it tries to find the system that this file was prepared for.

Usually, instead of using always "\n", use

 java.lang.System.getProperties().get("line.separator")


If your operating system is windows than you have to use \r\n for a new line, only \n won't work in windows, you can find more details here


This is because for Windows new line is: \r\n. In other OS \n will be good


when you need a new line, the best practice is to use the system newline string, by putting in System.getProperty("line.separator") where you want a line break.

That way, it will use the right new line for the platform you are making the file on (windows/mac/linux).

0

精彩评论

暂无评论...
验证码 换一张
取 消