Create a new line in Java's FileWriter
Asked Answered
B

10

52

I have coded the following FileWriter:

try {
    FileWriter writer = new FileWriter(new File("file.txt"), false);

    String sizeX = jTextField1.getText();
    String sizeY = jTextField2.getText();
    writer.write(sizeX);
    writer.write(sizeY);

    writer.flush();
    writer.close();
} catch (IOException ex) {}

Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.

What can be done to solve this?

Thank you.

Bybee answered 31/8, 2013 at 15:28 Comment(5)
writer.write("\n");Hulky
but it doesn't seem to work can you post results you get?Ravishment
If I try the "\n" method, there's nothing... just 1254 (12 for sizeX, 54 for sizeY)...Bybee
@lukulus could you try writer.write("\r\n"); or better writer.write(System.lineSeparator())?Ravishment
Do not edit the question to invalidate existing answers.Liddle
R
74

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out is also instance of PrintStream).

Ravishment answered 31/8, 2013 at 15:37 Comment(0)
F
33

Try System.getProperty( "line.separator" )

   writer.write(System.getProperty( "line.separator" ));
Forth answered 31/8, 2013 at 15:37 Comment(0)
D
13

Try wrapping your FileWriter in a BufferedWriter:

BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();

Javadocs for BufferedWriter here.

Davies answered 31/8, 2013 at 15:36 Comment(0)
D
3

Try:

String.format("%n");

See this question for more details.

Davies answered 31/8, 2013 at 15:33 Comment(0)
F
3

If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
        writer.write(jTextField1.getText());
        writer.write(jTextField2.getText());
        writer.newLine();
        writer.flush();
        writer.close();
} catch (IOException ex) {
    System.out.println("File could not be created");
}
Figurant answered 31/8, 2013 at 16:23 Comment(0)
A
3

Since 1.8, I thought this might be an additional solution worth adding to the responses:

Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException

StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());

If appending to the same file, perhaps use an Append flag with Files.write()

Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Aerostat answered 28/8, 2016 at 23:4 Comment(0)
L
1

Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.

Limekiln answered 26/1, 2015 at 12:18 Comment(2)
Smart one! Worked for me and should work for assignments. However for a project, any of the above highlighted approaches should be usedMiffy
yes, Notepad doesn't work with /n, but WordPad works fine with /n. Or need to use line.separator for Notepad.Peaked
L
1

One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.

try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
   pw.println();//new line
   pw.print("text");//print without new line
   pw.println(10);//print with new line
   pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
Liebfraumilch answered 23/2, 2021 at 19:10 Comment(0)
H
0

I would tackle the problem like this:

    BufferedWriter output;
    output = new BufferedWriter(new FileWriter("file.txt", true));
    String sizeX = jTextField1.getText();
    String sizeY = jTextField2.getText();
    output.append(sizeX);
    output.append(sizeY);
    output.newLine();
    output.close();

The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?

Hitoshi answered 31/8, 2013 at 15:53 Comment(0)
T
-1

using simple \n to break line in write file and normal output in java

Tournai answered 14/5, 2022 at 6:53 Comment(1)
Your answer doesn't add anything to the question, which hasn't been answered already.Pulmotor

© 2022 - 2024 — McMap. All rights reserved.