14 07 02 Create files

This short lesson continues the work on writing data to a text file in Java. We start from the example built in the previous video, where we created a FileWriter and wrote a single message. Now the goal is to feed an entire array of values into the file instead of a single fixed string.

We declare a String array containing five first names, then we open a FileWriter pointing at the destination file. To write all the names into the file we use a simple for loop that walks through the array and calls writer.write(...) for each entry. The previous example added a single "hello" message; here, each iteration writes one element of the array.

One name per line

  • Iterate the array with for (int i = 0; i < names.length; i++).
  • Inside the loop, call writer.write(names[i] + "\n").
  • Close the writer at the end so the buffer is flushed.

The escape sequence \n inserts a newline character after every name, so the output file ends up with one name per line instead of a single long string. This is a useful pattern as soon as we need to persist a list of items as a plain text file. In the next lesson we will see how to read the same file back into memory.

Summary

This lesson introduces file creation in Java by demonstrating how to create an array of five names and write them to a file, with each name on a separate line using line breaks. The tutorial sets up the foundation for file I/O operations and previews reading files in the next lesson.

Key points

  • Create an array containing five elements to store names
  • Use line breaks (backslash-n) to place each name on a separate line when writing to a file
  • Understand the basic file writing workflow before learning to read files
  • File I/O operations in Java require proper syntax for newline characters

FAQ

What is the purpose of using a line break when writing to a file in Java?

Line breaks (backslash-n or newline characters) separate each name on its own line in the file, making the output more organized and readable rather than having all names in a single line.

What will the next lesson cover?

The next lesson will demonstrate how to read files in Java, which is the complementary operation to creating and writing files.

Why start with a five-element array for this file creation lesson?

A small array of five elements serves as a manageable example to demonstrate the fundamental concept of writing data from a collection to a file without overwhelming complexity.