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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023