14 07 Create files

After working with exceptions, we now look at how to create a text file in Java. Imagine we need to write some data to a text file and read it back later: this lesson shows the simplest way to do it. The class we will use to write output is FileWriter.

We instantiate it with FileWriter writer = new FileWriter("file.txt");. The constructor expects a parameter because writing can target many different destinations: telling it which file to use is what makes the writer concrete. The IDE will mark the constructor as undefined until we import the class from java.io.

Because this constructor can throw an IOException, the compiler refuses to build the code unless we either wrap it in a try/catch or declare throws IOException on the surrounding method. For a quick example we add throws on main.

Writing and closing

  • writer.write("hello") inserts a string into the file.
  • Always finish with writer.close().
  • If you skip close(), the file may be created but stay empty because the buffer never flushes, and you leak a file handle.

Running the program creates the file with the text "hello" inside. You can find it at the root of the project or in the resources folder, depending on the path you used. The next lesson covers reading a file back from disk.

Summary

Learn how to create and write data to files in Java using the FileWriter class. This lesson demonstrates the essential steps: instantiating FileWriter with a filename, using the write() method to insert content, and—critically—calling close() to properly release resources and persist your data. Understanding file management in Java prevents resource leaks and ensures your written data is actually saved to disk.

Key points

  • FileWriter is the primary Java class for writing data to files; pass the filename to its constructor
  • Use the write() method to insert content into the file (e.g., write("Hello"))
  • Always close your file using the close() method to prevent resource leaks and ensure data is written to disk
  • Failure to close the file may result in the file being created but remaining empty—closing is mandatory
  • FileWriter operations can throw exceptions, so use try-catch blocks or declare throws in your method signature

FAQ

What happens if I don't close the FileWriter?

If you don't close the FileWriter, the file will be created but will be empty. The data you wrote using write() will not be persisted to disk, and you may encounter resource leaks.

What class should I use to write to files in Java?

Use the FileWriter class, which is part of Java's core file I/O library. Instantiate it by passing the filename to its constructor, then use the write() method to add content.

Do I need to handle exceptions when creating and writing files?

Yes, FileWriter operations can throw exceptions. You must either wrap your code in a try-catch block or declare throws in your method signature to handle these checked exceptions.