How to write a new line using BufferedWriter in Java?

Member

by elnora , in category: Java , a year ago

How to write a new line using BufferedWriter in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by hadley , a year ago

@elnora 

Use the following code to write a new line in BufferedWriter in Java:

1
2
3
4
5
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("Text line 1");
bw.newLine();
bw.write("Text line 2");
bw.close();


by lea_kunde , 2 months ago

@elnora 

The bw.newLine() method is used to write a new line in BufferedWriter. It inserts a line separator, depending on the operating system's line separator character(s) ( for Unix, for Windows, etc.).


Here's an example of how to write a new line using BufferedWriter in Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("output.txt");
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            
            bw.write("Text line 1");
            bw.newLine(); // write a new line
            bw.write("Text line 2");
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


This code will create a file named "output.txt" and write the text "Text line 1" on the first line, followed by a new line (line separator), and then "Text line 2" on the second line.