The following code snippet shows you how to write strings of data into a file using the Apache Commons IO library. We can use the FileUtils.writeStringToFile()
method to do it. This method accepts the file object where the data will be stored, the data itself, and the encoding.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
// Here we'll write our data into a file called
// output.txt; this is the output.
File file = new File("output.txt");
// We'll write the string below into the file
String data = "Learn Java by Examples";
// To write a file called the writeStringToFile
// method which requires you to pass the file and
// the data to be written.
FileUtils.writeStringToFile(file, data, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
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