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.