KaiquanMah commited on
Commit
eb94b4a
·
verified ·
1 Parent(s): b4c9a50

try (PrintWriter file = new PrintWriter("fileName.txt")) {...}

Browse files
Week 7: Enum, Generic Type, Streams, write to file, class diagram/12A. Writing to a File - PrintWriter+++ ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ As the course approaches its end, let's look at a few useful Java techniques and features.
2
+ Some of these have been briefly covered earlier in the course.
3
+ Note, however, that a lot is left out, you will learn more about Java, for example, in the Advanced Object-Oriented Programming course.
4
+
5
+
6
+ =============================================================================
7
+
8
+
9
+
10
+ Writing to a File
11
+
12
+ We've already discussed reading files.
13
+ Let's look at writing to a text file through a few simple examples.
14
+ The program writes the contents of a 'string list' to a file one line at a time.
15
+
16
+ A line feed character "\n" is added to each line when writing.
17
+
18
+
19
+ First, let's look at a simple example that creates a new file
20
+ and writes a couple of lines of text to it:
21
+
22
+ try (PrintWriter file = new PrintWriter("test.txt")){
23
+ file.write("Hi everyone!" + "\n");
24
+ file.write("Creating a new file here" + "\n");
25
+ file.write("That's it.");
26
+ }
27
+ catch (FileNotFoundException e) {
28
+ System.out.println("An error occurred: " + e);
29
+ }
30
+
31
+
32
+
33
+
34
+
35
+ As a second example, let's look at a method that takes a LIST of 'String' type and a FILE NAME as parameters.
36
+ The method writes the lines to the file.
37
+
38
+ First, an example using a for loop:
39
+
40
+ public static void writeFile(String fileName, ArrayList<String> lines) {
41
+ try (PrintWriter file = new PrintWriter(fileName)){
42
+ for (String line : lines) {
43
+ file.write(line + "\n");
44
+ }
45
+ } catch (FileNotFoundException e) {
46
+ System.out.println("An error occurred: " + e);
47
+ }
48
+ }
49
+
50
+
51
+
52
+
53
+
54
+ The same example, but utilizing streams:
55
+
56
+ public static void writeFile(String fileName, ArrayList<String> lines) {
57
+ try (PrintWriter file = new PrintWriter(fileName)){
58
+ lines.stream().forEach(line -> file.write(line + "\n"));
59
+ }
60
+ catch (FileNotFoundException e) {
61
+ System.out.println("An error occurred: " + e);
62
+ }
63
+ }
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+