Writing string data to file in java can be done using FileWriter
and FileOutputStream
classes or other. But writing safely will require lot of programing effort like provide encoding, check where file already exist or not and many more. This can be done very efficiently using FileUtils
class of Apache Commons IO Java library.
Below I have written one examples for writing and saving text to file system.
Library Information
Platform information
jdk-1.8.0_60, Java 8, Eclipse
Used library Name: Commons IO
Methods used: FileUtils
provides four method for writing text to file. These methods have all required checks and exception handling. For any production grade Java application it is good to use this utility as it will save effort.
It has four overloaded version with options like encoding and to append. If append is true
then I will append other wise it will overwrite data if file already exist. If encoding is not provided then it will user systems default encoding.
//Writes a String to a file creating the file if it does not exist.
static void writeStringToFile(File file, String data, Charset encoding)
//Writes a String to a file creating the file if it does not exist.
static void writeStringToFile(File file, String data, Charset encoding, boolean append)
//Writes a String to a file creating the file if it does not exist.
static void writeStringToFile(File file, String data, String encoding)
//Writes a String to a file creating the file if it does not exist.
static void writeStringToFile(File file, String data, String encoding, boolean append)
Example for writing text to file
package org.code4copy;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class StringToFile {
private static void writeText() throws IOException{
String data = "Hello! How are you?";
File dest = new File("C:\\example\\text.txt");
//With Default encoding and no append
FileUtils.writeStringToFile(dest, data);
System.out.println(FileUtils.readFileToString(dest));
//With Default encoding and append true
FileUtils.writeStringToFile(dest, data, true);
System.out.println(FileUtils.readFileToString(dest));
//With utf-8 encoding and append true
FileUtils.writeStringToFile(dest, data, Charset.forName("utf-8"),true);
System.out.println(FileUtils.readFileToString(dest));
}
public static void main(String[] args) {
try {
writeText();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of example
Hello! How are you?
Hello! How are you?Hello! How are you?
Hello! How are you?Hello! How are you?Hello! How are you?