Explain Codes LogoExplain Codes Logo

How do I create a file and write to it?

java
file-io
java-7
try-with-resources
Alex KataevbyAlex Kataev·Feb 12, 2025
TLDR

Create and write to a file with the File class and FileWriter in Java:

import java.io.*; public class SimpleFileWriter { public static void main(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.*; public class AdvancedFileWriter { public static void main(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.*; public class BinaryFileWriter { public static void main(String[] args) { String fileName = "example.bin"; byte[] data = new byte[]{ 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; public class CommonsFileWriter { public static void main(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; public class GuavaFileWriter { public static void main(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.