How To - Create & Write to a TextFile
Creating & Writing to a TextFile
The below methods is the easiest way to create and write to a Text File in Java, using the following I/O Components:
java.io.File
java.io.FileWriter
Writing to a text file, replacing contents
public class IOTest {
public void writeToTextFile(String content, String fileName) throws IOException {
File file = new File(fileName);
if (file.exists() != true) { // Checking if the file exists or not. If it doesn't exist create a new file.
file.createNewFile(); // Remeber to add catch clause for IOException
}
FileWriter writer = new FileWriter(file);
writer.write(content); // Could also use -- writer.append() -- method.
writer.flush();
writer.close();
}
}
Writing to an existing text file and keeping contents
public class IOTest {
public void writeToTextFile(String content, String fileName) throws IOException {
File file = new File(fileName);
if (file.exists() != true) { // Checking if the file exists or not. If not create a new file.
file.createNewFile(); // Remeber to add catch clause for IOException
}
// The "true" will append the new data, while retaining the old data.
FileWriter writer = new FileWriter(file, true);
writer.write(content); // Could also use -- writer.append() -- method.
writer.flush();
writer.close();
}
}
Advertisements