Create and write to a file with the File class and FileWriter in Java:
import java.io.*;
publicclassSimpleFileWriter{
publicstaticvoidmain(String[] args){
String fileName = "example.txt";
String content = "SomeContent";
try {
File file = new File(fileName);
if (file.createNewFile()) {
FileWriter writer = new FileWriter(file);
writer.write(content); // Spilling ink onto the parchment writer.close(); // Stashed the quill! } // Else, the file already exists; don't want to accidentally summon a demon by overwriting files, do we? } catch (IOException e) {
// A wild error has appeared! e.printStackTrace();
}
}
}
Advanced file writing: text files in Java 7+
Java 7 introduced some cool kids on the block: java.nio.file for easy file operations.
import java.nio.file.*;
import java.io.IOException;
import java.util.*;
publicclassAdvancedFileWriter{
publicstaticvoidmain(String[] args){
Path pathToFile = Paths.get("example.txt");
List<String> lines = Arrays.asList("Java is love,", "Java is life!");
try {
Files.write(pathToFile, lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
// Who needs coffee when you got Java. } catch (IOException e) {
// Debugging—it's like being the detective in a crime movie where you are also the murderer. e.printStackTrace();
}
}
}
Binary files: Efficiently managing bytes
For binary data, such as image or video files, OutputStream is your wingman.
import java.io.*;
publicclassBinaryFileWriter{
publicstaticvoidmain(String[] args){
String fileName = "example.bin";
byte[] data = newbyte[]{ 0x4a, 0x61, 0x76, 0x61 };
try (FileOutputStream fos = new FileOutputStream(fileName)) {
fos.write(data); // Java in bytes... Isn't it beautiful? } catch (IOException e) {
// IOException: Because users always close their streams.😂 e.printStackTrace();
}
}
}
Simplified file writing: Apache Commons IO & Google Guava
Writing files has never been easier with the help of Apache Commons IO and Google Guava.
Apache Commons IO
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
publicclassCommonsFileWriter{
publicstaticvoidmain(String[] args){
File file = new File("example.txt");
String data = "Easy peasy lemon squeezy!";
try {
FileUtils.writeStringToFile(file, data, "UTF-8");
// Writing files is easier than peeling a banana! } catch (IOException e) {
// Welcome to Catch statement. Enjoy your stay! e.printStackTrace();
}
}
}
Google Guava
import com.google.common.io.Files;
import java.io.File;
import java.nio.charset.StandardCharsets;
publicclassGuavaFileWriter{
publicstaticvoidmain(String[] args){
File file = new File("example.txt");
String data = "Simplified I/O with Google Guava!";
try {
Files.write(data, file, StandardCharsets.UTF_8);
// Guava makes I/O as simple as ABC. } catch (IOException e) {
// Catching exceptions is a hobby, isn't it? e.printStackTrace();
}
}
}
Resources handling, File existence and encoding considerations
Ensuring resource releasing
Always wrap I/O operations in a try-with-resources block or manually close streams to prevent resource leakage.
Checking file existence before writing
Ensure existence of target file with Files.exists() before writing operations to prevent accidental data loss.
Consistent text encoding
Ensure reliable text output by specifying the charset when writing text files.