0

Simply trying to move to a new line after printing each element inside of notepad. Some searching has yielded uses of \r\n, but that doesn't seem to work either.

for(String element : misspelledWords)
                {
                    writer.write(element + "\n");
                }
user3743340
  • 47
  • 1
  • 6
  • If you are using BufferedWriter then there is a method newLine() which will insert a new line refer http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine() Can you please mention whcih writer class you are using – Ashok_Pradhan Jun 27 '14 at 04:54
  • The expected output would be: word (new line) word2 (newline) word3 – user3743340 Jun 27 '14 at 05:01
  • The current output is:wordword2word3 – user3743340 Jun 27 '14 at 05:01
  • Use `System.getProperty("line.separator")` instead, because it is compile time OS independent. – Smutje Jun 27 '14 at 05:03
  • possible duplicate of [Is there a Newline constant defined in Java like Environment.Newline in C#?](http://stackoverflow.com/questions/247059/is-there-a-newline-constant-defined-in-java-like-environment-newline-in-c) – Smutje Jun 27 '14 at 05:09

2 Answers2

4

try this

BufferedWriter writer = new BufferedWriter(new FileWriter("result.txt"));       
    for (String element : misspelledWords) {
        writer.write(element);
        writer.newLine();
    }

Adding line separator at the end (like "\n") should work on most OS,but to be on safer side you should use System.getProperty("line.separator")

Ashok_Pradhan
  • 1,159
  • 11
  • 13
0

Open your file in append mode like this FileWriter(String fileName, boolean append) when you want to make an object of class FileWrite

in constructor.

 File file = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects\\addNewLinetoTxtFile\\src\\addnewlinetotxtfile\\a.txt");
    try (Writer newLine = new BufferedWriter(new FileWriter(file, true));) {
       newLine.write("New Line!");
       newLine.write(System.getProperty( "line.separator" ));
    } catch (IOException e) {

    }

Note:

"line.separator" is a Sequence used by operating system to separate lines in text files

source: http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58