Repository navigation
Expand file tree
/
Copy pathch8_filehandling.ptx
More file actions
648 lines (566 loc) · 28.7 KB
/
Copy pathch8_filehandling.ptx
File metadata and controls
648 lines (566 loc) · 28.7 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
<?xml version="1.0"?>
<!-- Generated by Docutils 0.19 -->
<chapter xml:id="file-handling">
<title>File Handling</title>
<section xml:id="class-imports">
<title>Class Imports</title>
<p>
File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like <c>math</c> do need to be imported. Consider the following.
</p>
<program xml:id = "file-class-import-Python-example" interactive="activecode" language="python">
<code>
import math
print(math.sqrt(25))
</code>
</program>
<p>
Delete the first line that says <c>import math</c> and see what happens. The <c>import math</c> is needed. The same program in Java would look like this:
</p>
<program xml:id = "file-class-import-Java-example" interactive="activecode" language="java">
<code>
import java.lang.Math;
public class SquareRoot {
public static void main(String[] args) {
System.out.println(Math.sqrt(25));
}
}
</code>
</program>
<p>
Note the use of <c>import java.lang.Math;</c> in the above to import the <c>Math</c> class. Unlike Python, Java requires explicit <c>import</c> for most libraries, including the <c>Math</c> class and many classes related to file handling.
</p>
<p>
Much like the <c>Math</c> class, in order for your program to work with files you need use <c>import</c>. Java includes a class called <c>File</c> in the <c>io</c> library. This class allows you to create <c>File</c> objects, and use its public methods.
</p>
<program xml:id="io-file-import" language="java">
import java.io.File;
</program>
<p>
The <c>Scanner</c> class from the <c>util</c> library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.
</p>
<program xml:id="util-scanner-import" language="java">
import java.util.Scanner;
</program>
<p>
The <c>FileWriter</c> class can be used to write to files. In the same way that the <c>Scanner</c> class isn't needed unless the program will read from a file, the <c>FileWriter</c> class isn't needed unless the program will write to a file.
</p>
<program xml:id="io-filewriter-import" language="java">
import java.io.FileWriter;
</program>
<p>
Finally, these last two classes provide error handling and must be used in tandem with the <c>File</c> class when reading from or writing to files. <c>IOException</c> handles file creation and writing errors, while <c>FileNotFoundException</c> handles errors when trying to read files.
</p>
<program xml:id="io-exception-imports" language="java">
import java.io.IOException;
import java.io.FileNotFoundException;
</program>
</section>
<section xml:id="creating-files">
<title>Creating Files</title>
<p>
We will now create a <c>File</c> object. It is important to create a meaningful name for the <c>File</c> object. We will call ours <c>myFile</c>, and we will call our class <c>CreateFileObject</c>.
</p>
<program xml:id="create-file-object-java" interactive="activecode" language="java" add-files="myfile-created">
<code>
import java.io.File;
public class CreateFile {
public static void main(String[] args) {
// First, create a File object that represents "myfile.txt"
File myFile = new File("myfile.txt");
// Next, print the file path (just the filename.)
System.out.println(myFile);
}
}
</code>
</program>
<note>
<p>
<c>myFile</c> is the name of the object within the program, while <c>myfile.txt</c> is the name of the file itself and will be the file name if the operation that creates the file is successful.
</p>
</note>
<p>
Now let's learn how to make a file in Java. In Python. files can be made using the <c>open()</c> function on a file path that doesn't exist yet. Similarly, in Java you create a file by using the <c>createNewFile()</c> method on a <c>File</c> object. This method actually does the work of creating a file and saving it in the current working directory, and returns a boolean value of either true or false if the file is successfully created. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created. Finally, we encase this code within try/catch blocks. This step is required in the Java code to be compiled. If try/catch blocks using <c>IOException</c> are not included, there will be compilation errors.
</p>
<p>
First, lets look at the equivalent Python code:
</p>
<program xml:id="create-file-python" interactive="activecode" language="python">
<code>
filename = "newfile.txt"
print("Attempting to write to '" + filename + "' using 'w' mode...")
try:
with open(filename, 'w') as f:
f.write("This file was created using 'w' mode.")
print("SUCCESS: The file '" + filename + "' was created or overwritten.")
except Exception as e:
# This would only catch other unexpected errors
print("An unexpected error occurred during write: " + str(e))
</code>
</program>
<p>
Now, let's look at Java code that accomplishes the same task:
</p>
<program xml:id="create-file-java" interactive="activecode" language="java">
<code>
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
File myFile = new File("newfile.txt");
try {
if (myFile.createNewFile()) {
System.out.println("The file " + myFile.getName() + " was created successfully.");
} else {
System.out.println("The file " + myFile.getName() + " already exists.");
}
} catch (IOException e) {
// This code runs if an IOException occurs
System.out.println("An error occurred while creating the file.");
e.printStackTrace(); // This prints the stack trace for more detailed error info
}
}
}
</code>
</program>
<note>
<p>
You may have noticed the use of another method from the File class; <c>getName()</c>. This method returns a string containing the name of the file.
</p>
</note>
</section>
<section xml:id="reading-files">
<title>Reading Files</title>
<p>
Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line's content. In Java, you read files in a very similar way, however in Java we will use the <c>Scanner</c> class in order to iterate through the lines.
</p>
<p>
Consider the following Python code example that reads each line of the file and prints it to the console.
</p>
<datafile label="myfile-read" filename="myfile.txt" xml:id= "myfile-read" editable="no">
<pre>
1
2
3
4
5
6
7
8
</pre>
</datafile>
<program xml:id="file-read-python" interactive="activecode" language="python" add-files="myfile-read">
<code>
filename = "myfile.txt"
try:
# Attempt to open the file in read mode ('r')
with open(filename, "r") as file_reader:
# Iterate over each line in the file
for line in file_reader:
print(line.strip())
except:
#catches if the file doesn't exist or can't be written to
print("file could not be opened")
</code>
</program>
<p>
The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the <c>Scanner</c> object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.
</p>
<program xml:id="file-read-java" interactive="activecode" language="java" add-files= "myfile-read">
<code>
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main (String[] args) {
String filename = "myfile.txt";
try (Scanner fileReader = new Scanner(new File(filename))) {
while (fileReader.hasNextLine()) {
String data = fileReader.nextLine();
System.out.println(data);
}
}
catch (FileNotFoundException e) {
System.out.println("Error: The file '" + filename + "' was not found.");
}
}
}
</code>
</program>
<p>
You may have noticed that there are some new methods you haven't seen yet. The <c>hasNextLine()</c> method checks if there is a next line in the file, and returns <c>false</c> if there isn't. This method allows us to iterate over every line till there is no next line. The <c>nextLine()</c> method of the Scanner object returns the next line in the file as a string.
</p>
</section>
<section xml:id="writing-to-files">
<title>Writing to Files</title>
<p>
The <c>createNewFile()</c> method is useful for attempting to create files and reporting if the operation was successful, however, <c>createNewFile()</c> does not write anything to files it creates. In fact, if you use <c>createNewFile()</c> to create a <c>.txt</c> file and then open the file, the file will be blank.
</p>
<p>
Let us create the framework for a class that will write to a file. Let's call this class <c>WriteFile</c>:
</p>
<program xml:id="write-file-class-java" language="java">
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteFile {
public static void main(String[] args) {
}
}
</program>
<p>
Next, we will create a <c>FileWriter</c> object. Let's call it <c>myWriter</c>. The equivalent Python code to this operation is:
</p>
<program xml:id="filerwriter-object-python" language="python">
with open("myfile.txt", "w") as myWriter:
</program>
<p>
The Java code to create a <c>FileWriter</c> object is:
</p>
<program xml:id="filerwriter-object-java" language="java">
FileWriter myWriter = new FileWriter("myfile.txt");
</program>
<p>
In this next step, we will use the <c>write()</c> method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The <c>write()</c> method takes most standard data types. First, how this step is completed with Python:
</p>
<program xml:id="write-and-close-python" language="python">
my_writer.write("File successfully updated!")
</program>
<p>
And the Java equivalent. This is almost completely identical except for the second line, which is very important!
</p>
<program xml:id="write-and-close-java" language="java">
myWriter.write("File successfully updated!");
myWriter.close();
</program>
<note>
<p>
The <c>close()</c> method is being used after writing to the file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided!
</p>
</note>
<p>
Next, we will again add the required try/catch blocks utilizing the <c>IOException</c> class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:
</p>
<program xml:id="file-try-catch-python" language="python" add-files = "my-file-8-4-2">
try:
with open("myfile.txt", "w") as my_writer:
my_writer.write("File successfully updated!")
print("File successfully written to.")
except OSError as e:
print("An error occurred.")
import traceback
traceback.print_exc()
</program>
<p>
And the equivalent Java code:
</p>
<program language="java" xml:id="file-try-catch-java">
try {
FileWriter myWriter = new FileWriter("myfile.txt");
myWriter.write("File successfully updated!");
myWriter.close();
System.out.println("File successfully written to.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
</program>
<p>
And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:
</p>
<datafile label="my-file-8-4-4" filename="myfile.txt" xml:id= "my-file-8-4-4" editable="yes">
<pre>
</pre>
</datafile>
<program xml:id="file-write-full-python" interactive="activecode" language="python" add-files="my-file-8-4-4">
<code>
try:
with open("myfile.txt", "w") as my_writer:
my_writer.write("File successfully updated!")
print("File successfully written to.")
except OSError:
print("An error occurred.")
import traceback
traceback.print_exc()
</code>
</program>
<p>
The completed Java code:
</p>
<datafile label="my-file-8-4-5" filename="myfile.txt" xml:id= "my-file-8-4-5" editable="yes">
<pre>
</pre>
</datafile>
<program xml:id="file-write-full-java" interactive="activecode" language="java" add-files = "my-file-8-4-5">
<code>
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("myfile.txt");
myWriter.write("File successfully updated!");
myWriter.close();
System.out.println("File successfully written to.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
</code>
</program>
<note>
<p>
If a file does not already exist (for example, <c>myfile.txt</c> does not exist), the <c>write()</c> method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the <c>createNewFile()</c> method avoids overwriting files that already exist. Imagine a file with the name <c>myfile.txt</c> already exists and contains important information. Attempting to create a file using the <c>write()</c> method will delete that data forever.
</p>
</note>
<p>
Speaking of overwriting data, what if we want to append text to the end of any text already in <c>myfile.txt</c>? To accomplish this, we can pass a <c>boolean</c> argument along with the file name when creating a new data argument:
</p>
<program xml:id="append-true" language="java">
FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
</program>
<p>
Now, when we use <c>write()</c> method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the <c>boolean</c> argument:
</p>
<datafile label="my-file-8-4-6" filename="myfile" xml:id= "my-file-8-4-6" editable="yes">
<pre>
</pre>
</datafile>
<program xml:id="file-write-with-append" interactive="activecode" language="java" add-files = "my-file-8-4-6">
<code>
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
myWriter.write("File successfully updated!");
myWriter.close();
System.out.println("File successfully written to.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
</code>
</program>
<p>
Then if we run the program twice, the contents of <c>myfile.txt</c> would be:
</p>
<pre>
File successfully updated!File successfully updated!
</pre>
<p>
This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the <c>\n</c> newline character:
</p>
<program xml:id="newline" language="java">
myWriter.write("File successfully updated!\n"); // Added newline character
myWriter.close();
</program>
<p>
Running the code with the newline character twice will result in the following contents in myfile.txt:
</p>
<pre>
File successfully updated!
File successfully updated!
</pre>
</section>
<section xml:id="file-delete">
<title>Deleting Files</title>
<p>
Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. Here is the <c>CreateFile</c> class from before that will be used to create a file that we will soon delete:
</p>
<program xml:id="create-file-to-delete-java" interactive="activecode" language="java">
<code>
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
File myFile = new File("myfile.txt");
try {
if (myFile.createNewFile()) {
System.out.println("The file " + myFile.getName() + " was created successfully.");
} else {
System.out.println("The file " + myFile.getName() + " already exists.");
}
} catch (IOException e) {
// This code runs if an IOException occurs
System.out.println("An error occurred while creating the file.");
e.printStackTrace(); // This prints the stack trace for more detailed error info
}
}
}
</code>
</program>
<p>
And finally, we have Java code that deletes a file. We will call this class <c>DeleteFile</c>:
</p>
<program xml:id="delete-file-java" interactive="activecode" language="java">
<code>
import java.io.File;
import java.io.IOException;
public class DeleteFile {
public static void main(String[] args) {
try {
File myFile = new File("myfile.txt");
// Create the file (does nothing if it already exists)
myFile.createNewFile();
System.out.println("File created: " + myFile.getName());
// Delete the file
if (myFile.delete()) {
System.out.println("Deleted " + myFile.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code>
</program>
<p>
Note that this is almost identical to the code within the <c>try</c> block of the <c>CreateFile</c> class that we made earlier. The key difference is the use of the <c>delete()</c> method which will delete the file with the name that was linked to the myFile object. Similar to the <c>createNewFile()</c> method, it will return <c>true</c> if the file exists and can be deleted, and <c>false</c> if the file cannot be deleted.
</p>
</section>
<section xml:id="chapter8_summary">
<title>Summary & Reading Questions</title>
<p><ol label="1">
<li>
<p>To work with files in Java, you must import specific classes like <c>java.io.File</c>, <c>java.io.FileWriter</c>, and handle exceptions such as <c>IOException</c>.</p>
</li>
<li>
<p>You can create a new file using <c>File.createNewFile()</c>, which returns <c>true</c> if the file is created and <c>false</c> if it already exists.</p>
</li>
<li>
<p>Reading from files is done using a <c>Scanner</c> attached to a <c>File</c>, often with a loop using <c>hasNextLine()</c> and <c>nextLine()</c>.</p>
</li>
<li>
<p>To write to a file, use a <c>FileWriter</c> object and call methods like <c>write()</c> and <c>close()</c> to save and finish the output.</p>
</li>
<li>
<p>You can delete a file using the <c>delete()</c> method on a <c>File</c> object, which returns <c>true</c> if successful.</p>
</li>
</ol></p>
<reading-questions xml:id="rqs-summary8">
<exercise label="summary-imports">
<statement>
<p>Which import is needed to create and manipulate files in Java?</p>
</statement>
<choices>
<choice>
<statement>
<p>import java.util.File;</p>
</statement>
<feedback>
<p>No, <c>File</c> is part of the <c>java.io</c> package, not <c>java.util</c>.</p>
</feedback>
</choice>
<choice correct="yes">
<statement>
<p>import java.io.File;</p>
</statement>
<feedback>
<p>Correct! <c>File</c> is found in the <c>java.io</c> package.</p>
</feedback>
</choice>
<choice>
<statement>
<p>import java.file.Input;</p>
</statement>
<feedback>
<p>No, this is not a valid import for file operations.</p>
</feedback>
</choice>
<choice>
<statement>
<p>import java.system.io.*;</p>
</statement>
<feedback>
<p>No, there is no such package in Java.</p>
</feedback>
</choice>
</choices>
</exercise>
<exercise label="summary-createfile">
<statement>
<p>What does <c>myFile.createNewFile()</c> return if the file already exists?</p>
</statement>
<choices>
<choice>
<statement>
<p>It throws an exception.</p>
</statement>
<feedback>
<p>No, it only throws an exception for access errors, not for existing files.</p>
</feedback>
</choice>
<choice correct="yes">
<statement>
<p>false</p>
</statement>
<feedback>
<p>Correct! It returns <c>false</c> if the file already exists.</p>
</feedback>
</choice>
<choice>
<statement>
<p>true</p>
</statement>
<feedback>
<p>No, <c>true</c> is returned only when the file is successfully created.</p>
</feedback>
</choice>
<choice>
<statement>
<p>null</p>
</statement>
<feedback>
<p>No, <c>null</c> is not a valid return value for this method.</p>
</feedback>
</choice>
</choices>
</exercise>
<exercise label="summary-readscanner">
<statement>
<p>Which method checks if a file has more lines to read using a Scanner?</p>
</statement>
<choices>
<choice>
<statement>
<p>nextLine()</p>
</statement>
<feedback>
<p>No, <c>nextLine()</c> retrieves the next line, but does not check for availability.</p>
</feedback>
</choice>
<choice>
<statement>
<p>hasMore()</p>
</statement>
<feedback>
<p>No, this is not a method of <c>Scanner</c>.</p>
</feedback>
</choice>
<choice correct="yes">
<statement>
<p>hasNextLine()</p>
</statement>
<feedback>
<p>Correct! This checks if there is another line available to read.</p>
</feedback>
</choice>
<choice>
<statement>
<p>canReadLine()</p>
</statement>
<feedback>
<p>No, this is not a standard method in the Scanner class.</p>
</feedback>
</choice>
</choices>
</exercise>
</reading-questions>
</section>
</chapter>