How Java uses the PrintWriter class to write text content to a txt file
To write text content to a txt file using the PrintWriter class, you need to perform the following steps:
1. Create a PrintWriter object and connect it to the file you want to write to. PrintWriter can be initialized using FileWriter or BufferedWriter.
2. Use PrintWriter's println() or print() methods to write text to a file.
3. Close the PrintWriter stream and ensure that the written content is flushed to the file.
The following is an example code for writing text content to a txt file using the PrintWriter class:
import java.io.*;
public class FileWriterExample {
public static void main(String[] args) {
//Create a PrintWriter object and connect to a file
try (PrintWriter writer = new PrintWriter(new FileWriter("output.txt"))) {
//Write Text Content
writer.println("Hello, World!");
writer.print("This is a text file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code will write two lines of text to a file named "output. txt". The first line is "Hello, World!", and the second line is "This is a text file.
If you want to use Maven dependencies to add third-party libraries, you can add the following dependencies:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>
After using this dependency, you can use the 'write (String filePath, String content, Charset encoding)' method in the 'org. apache. commons. io. FileUtils' class to write text content. The following is the sample code:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileUtilsExample {
public static void main(String[] args) {
String filePath = "output.txt";
String content = "Hello, World!
This is a text file.";
try {
FileUtils.write(new File(filePath), content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code will use the 'FileUtils. write()' method to write the text content to a file named 'output. txt'.