Search code examples
javatext-filesdataoutputstream

Writing to text files in Java


I have a method that writes a string to a text file using a DataOutputStream and the .writeBytes(String) method. If I write a string with a newline character, for example "I need \n help!", the new line is not displayed in notepad or other basic text editors. However, it does show up in WordPad, MS Word, etc. Why is this and can I fix it?


Solution

  • Mostly by using real text editors, which Notepad isn't.

    You need to write system-specific newlines if you're not going to use a text editor that understands different flavors, or filter the file through something that does the conversion for you.

    System.getProperty("line.separator");
    

    This will give you an OS-specific line separator. It's less useful than you think.

    System.out.printf("%n");
    

    This does the same (and is available in String.format as well); also less useful than you think. It's more an editor thing, since any file could exist on any system, edited with any editor.