KaiquanMah's picture
try (PrintWriter file = new PrintWriter("fileName.txt")) {...}
eb94b4a verified
As the course approaches its end, let's look at a few useful Java techniques and features.
Some of these have been briefly covered earlier in the course.
Note, however, that a lot is left out, you will learn more about Java, for example, in the Advanced Object-Oriented Programming course.
=============================================================================
Writing to a File
We've already discussed reading files.
Let's look at writing to a text file through a few simple examples.
The program writes the contents of a 'string list' to a file one line at a time.
A line feed character "\n" is added to each line when writing.
First, let's look at a simple example that creates a new file
and writes a couple of lines of text to it:
try (PrintWriter file = new PrintWriter("test.txt")){
file.write("Hi everyone!" + "\n");
file.write("Creating a new file here" + "\n");
file.write("That's it.");
}
catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e);
}
As a second example, let's look at a method that takes a LIST of 'String' type and a FILE NAME as parameters.
The method writes the lines to the file.
First, an example using a for loop:
public static void writeFile(String fileName, ArrayList<String> lines) {
try (PrintWriter file = new PrintWriter(fileName)){
for (String line : lines) {
file.write(line + "\n");
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e);
}
}
The same example, but utilizing streams:
public static void writeFile(String fileName, ArrayList<String> lines) {
try (PrintWriter file = new PrintWriter(fileName)){
lines.stream().forEach(line -> file.write(line + "\n"));
}
catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e);
}
}