File size: 1,891 Bytes
eb94b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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);
    }
}