Explain Codes LogoExplain Codes Logo

How do I save a String to a text file using Java?

java
file-io
best-practices
resource-management
Anton ShumikhinbyAnton Shumikhin·Aug 29, 2024
TLDR

Here's a quick snippet using Files.write from java.nio.file:

import java.nio.file.Files; import java.nio.file.Path; String content = "Your string"; // Change this to your actual string! Path path = Path.of("destination.txt"); // Pick your file's name and path! Files.write(path, content.getBytes());

This method takes care of encoding and exceptions, so your string becomes a high-packed byte courier heading straight to destination.txt.

BufferedWriter - the speedy hauler

Working with voluminous strings or writing frequently? Opt for a BufferedWriter for enhanced velocity:

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; String content = "A journey of a thousand miles begins with a single... uh, character"; try (BufferedWriter writer = new BufferedWriter(new FileWriter("LargeData.txt"))) { writer.write(content); // Yes, you got it right. It's basically 'BufferedWriter' on steroids 💪 } catch(IOException e) { System.out.println("Oops! Something went wrong. 😕"); }

Apache Commons IO - the Swiss Army knife

For those relying on Apache Commons IO, FileUtils.writeStringToFile is your one-stop function:

import org.apache.commons.io.FileUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; try { FileUtils.writeStringToFile(new File("fancyApache.txt"), "Look, Ma! Apache's doing all the work!", StandardCharsets.UTF_8); // Because commons do have common sense 😉 } catch(IOException e) { System.out.println("Everything's under control... except for this. 🆘"); }

Remember to set the encoding, since strings lost in translation aren't funny.

PrintStream - the multi-talented screenshot taker

PrintStream, when used with FileOutputStream, can handle different character sets or automatic flushing, like a boss!

import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; try { PrintStream out = new PrintStream(new FileOutputStream("fancyText.txt"), true, "UTF-8"); out.println("Hello World! ενδιαφέρον κόσμο! こんにちは世界!"); // Polyglots, rejoice! Different languages? No problem! 🌎 out.close(); } catch (UnsupportedEncodingException | FileNotFoundException e) { System.out.println("What do we say to encoding errors? Not today! But, it happened. 😑"); }

Potential detours and how to navigate them

IOError? More like IOEr... not.

Always handle IOExceptions. They signal that something is off with the I/O process, be it a filesystem failure or indigestion from eating too much disk space.

Where's the file?

FileNotFoundExceptions are unpleasant surprises. Handle them gracefully:

try (PrintWriter out = new PrintWriter("file_that_does_not_exist.txt")) { out.println("Not all those who wander are lost... except FileNotFound."); } catch (FileNotFoundException e) { System.out.println("File not found! Maybe it's on a vacation? ¯\\_(ツ)_/¯"); }

Not properly closing? Resource leaks are not on our watch!

Try-with-resources works like a wonder in ensuring proper closure of files and preventing resource leaks:

try (BufferedWriter out = new BufferedWriter(new FileWriter("goodbyeLeak.txt"))) { out.write("Closures are a closure for memory leaks!"); } catch(IOException e) { System.out.println("Another one bytes the dust... or does it? 💀"); }

Best practices for smoother sailing

To null or not to null?

To prevent NullPointerException, check if the BufferedWriter is not null before closing it:

BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter("nullPatrol.txt")); out.write("To null or not to null? Not here!"); } catch (IOException e) { System.out.println("IO, oh no! 😭"); } finally { if (out != null) { try { out.close(); // Checked for null? You have my consent! ✅ } catch (IOException e) { System.out.println("So close, yet so far... 🎵"); } } }

The FileWriter's manual

write(string) can be your friend for granular control over how the file contents are written:

try (FileWriter writer = new FileWriter("pieceByPiece.txt")) { writer.write("String building"); writer.write(", piece by piece."); // Yes, I'm a writer. A FileWriter. 😎 } catch (IOException e) { System.out.println("Yeah, IO, IO, it's down the stack trace we go... 🎵"); }