Java Write to File: Create & Write Text Files
You can use the FileWriter class in Java to create and write to text files. Here is an example code to create a file named example.txt and write data to it:
import java.io.FileWriter;
import java.io.IOException;
public class CreateAndWriteFile {
public static void main(String[] args) {
String data = "Hello, World!";
try {
FileWriter writer = new FileWriter("example.txt");
writer.write(data);
writer.close();
System.out.println("文件创建和写入成功!");
} catch (IOException e) {
System.out.println("发生错误:" + e.getMessage());
}
}
}
The code above first defines a string variable named data, which contains the data to be written to the file.
Next, in the try block, we instantiate a FileWriter object and pass the filename “example.txt” to be created.
Next, we utilize writer.write(data) to write the string data to the file.
Finally, we closed the file writer and printed a successful message.
If any IO exception occurs, we catch it in the catch block and print out the error message.
Please note that this code will create and write to a new file. If a file named “example.txt” already exists, it will be overwritten. If you want to append data to the end of an existing file instead of replacing it, you can set the second boolean parameter of the FileWriter constructor to true as shown below:
FileWriter writer = new FileWriter("example.txt", true);