Here is a code example for creating text file and put some texts in it. This program will create a file called write.txt
. To create and write a text file we do the following steps:
File file = new File("write.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Below is the complete code snippet:
package org.kodejava.io;
import java.io.*;
public class WriteTextFileExample {
public static void main(String[] args) {
File file = new File("write.txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = "The quick brown fox" +
System.getProperty("line.separator") + "jumps over the lazy dog.";
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
To read a text file see the following example: How do I read a text file using BufferedReader?.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024