|
1 | 1 | <?xml version="1.0"?> |
2 | 2 |
|
3 | 3 | <!-- Generated by Docutils 0.19 --> |
4 | | -<chapter xml:id="filemmanipulation"> |
| 4 | +<chapter xml:id="file-handling"> |
5 | 5 | <title>File Handling</title> |
6 | 6 |
|
7 | | - <section xml:id="file-class-import"> |
| 7 | + <section xml:id="class-imports"> |
8 | 8 | <title>Class Imports</title> |
9 | 9 | <p> |
10 | | - File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy 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. |
| 10 | + 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. |
11 | 11 | </p> |
12 | 12 | <program xml:id = "file-class-import-Python-example" interactive="activecode" language="python"> |
13 | 13 | <code> |
|
17 | 17 | </program> |
18 | 18 |
|
19 | 19 | <p> |
20 | | - The same program in Java would look like this: |
| 20 | + 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: |
21 | 21 | </p> |
22 | 22 | <program xml:id = "file-class-import-Java-example" interactive="activecode" language="java"> |
23 | 23 | <code> |
|
31 | 31 | </code> |
32 | 32 | </program> |
33 | 33 | <p> |
34 | | - Note the use of <c>import java.lang.Math;</c> in the above to import the Math class. Unlike Python, Java requires explicit imports for most libraries, including the <c>Math</c> class and many different classes for file handling. |
| 34 | + 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. |
35 | 35 | </p> |
36 | 36 |
|
37 | 37 | <p> |
38 | | - Much like the Math class, in order for your program to work with files you need to import classes from libraries. Java includes a class called <c>File</c> in the <c>io</c> library. This class allows you to create File objects, and use its public methods. the following code imports the <c>File</c> class and creates a <c>File</c> object called myFile. for now focus on how the class is imported and used in the program; We will cover the <c>IOException</c> class and <c>createNewFile</c> method later. |
| 38 | + 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. the following code imports the <c>File</c> class and creates a <c>File</c> object called myFile. for now focus on how the class is imported and used in the program; We will cover the <c>IOException</c> class and <c>createNewFile</c> method later. |
39 | 39 | </p> |
40 | 40 | <program xml:id = "file-class-import-io-example" interactive="activecode" language="java"> |
41 | 41 | <code> |
|
82 | 82 |
|
83 | 83 | </section> |
84 | 84 |
|
85 | | - <section xml:id="create-file"> |
| 85 | + <section xml:id="creating-files"> |
86 | 86 | <title>Creating Files</title> |
| 87 | + |
| 88 | + |
| 89 | + <p> |
| 90 | + 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>. |
| 91 | + </p> |
| 92 | + <datafile label="myfile-created" filename="myfile.txt" xml:id= "myfile-created" editable="yes"> |
| 93 | + <pre> |
| 94 | + empty file |
| 95 | + </pre> |
| 96 | + </datafile> |
| 97 | + <program xml:id="create-file-java" interactive="activecode" language="java" add-files="myfile-created"> |
| 98 | + <code> |
| 99 | + import java.io.File; |
| 100 | + public class Main { |
| 101 | + public static void main(String[] args) { |
| 102 | + File myFile = new File("myfile.txt"); |
| 103 | + System.out.println(myFile); |
| 104 | + } |
| 105 | + } |
| 106 | + </code> |
| 107 | + </program> |
| 108 | + |
| 109 | + <note> |
| 110 | + <p> |
| 111 | + <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. |
| 112 | + </p> |
| 113 | + </note> |
| 114 | + |
| 115 | + |
87 | 116 | <p> |
88 | 117 | 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 try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory. |
89 | 118 | </p> |
|
92 | 121 | First, lets look at the equivalent Python code: |
93 | 122 | </p> |
94 | 123 |
|
95 | | - <program xml:id="creat-file-exp-2" interactive="activecode" language="python"> |
| 124 | + <program xml:id="create-file-python" interactive="activecode" language="python"> |
96 | 125 | <code> |
97 | 126 | filename = "newfile.txt" |
98 | 127 | print("Attempting to write to '" + filename + "' using 'w' mode...") |
|
140 | 169 | 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. |
141 | 170 | </p> |
142 | 171 | </note> |
143 | | - </section> |
144 | | - |
| 172 | + </section> |
145 | 173 |
|
146 | | - <section xml:id="file-read"> |
| 174 | + <section xml:id="reading-files"> |
147 | 175 | <title>Reading Files</title> |
148 | 176 |
|
149 | 177 | <p> |
150 | | - Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: |
151 | | - </p> |
152 | | - <datafile label="my-file" filename="myfile.txt" xml:id= "my-file" editable="no"> |
| 178 | + 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. |
| 179 | + </p> |
| 180 | + <p> |
| 181 | + Consider the following Python code example that reads each line of the file and prints it to the console. |
| 182 | + </p> |
| 183 | + <datafile label="myfile-read" filename="myfile.txt" xml:id= "myfile-read" editable="no"> |
153 | 184 | <pre> |
154 | 185 | 1 |
155 | 186 | 2 |
|
161 | 192 | 8 |
162 | 193 | </pre> |
163 | 194 | </datafile> |
164 | | - |
165 | | - |
166 | | - <program xml:id="file-read-exp1" interactive="activecode" language="java" add-files= "my-file"> |
167 | | - <code> |
168 | | - import java.io.File; |
169 | | - import java.io.FileNotFoundException; |
170 | | - import java.util.Scanner;public class Main { |
171 | | - public static void main(String[] args) { |
172 | | - try { |
173 | | - File myFile = new File("myfile.txt"); |
174 | | - Scanner fileReader = new Scanner(myFile); |
175 | | - System.out.println("Reading from file: " + myFile.getName()); |
176 | | - while (fileReader.hasNextLine()) { |
177 | | - String data = fileReader.nextLine(); |
178 | | - System.out.println(data); |
179 | | - } |
180 | | - fileReader.close(); // Close the scanner to release the file |
181 | | - } catch (FileNotFoundException e) { |
182 | | - System.out.println("An error occurred: The file was not found."); |
183 | | - e.printStackTrace(); |
184 | | - } |
185 | | - } |
186 | | - } |
187 | | - </code> |
188 | | - </program> |
189 | | - |
190 | | - <p> |
191 | | - We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: |
192 | | - </p> |
193 | | - |
194 | | - <program xml:id="file-read-exp2" interactive="activecode" language="java" add-files="my-file"> |
195 | | - <code> |
196 | | - import java.io.File; |
197 | | - import java.io.FileNotFoundException; |
198 | | - import java.util.Scanner; |
199 | | - public class Main { |
200 | | - public static void main(String[] args) { |
201 | | - // This 'try-with-resources' statement handles opening the file |
202 | | - // and guarantees it is closed automatically, which is best practice. |
203 | | - try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { |
204 | | - |
205 | | - // If this line is reached, the file was opened successfully. |
206 | | - System.out.println("Success! The file 'myfile.txt' is now open."); |
207 | | - |
208 | | - } catch (FileNotFoundException e) { |
209 | | - |
210 | | - // This block runs only if 'myfile.txt' does not exist. |
211 | | - System.out.println("Error: The file 'myfile.txt' could not be found."); |
212 | | - } |
213 | | - } |
214 | | - } |
215 | | - </code> |
216 | | - </program> |
217 | | - |
218 | | - <p> |
219 | | - The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.: |
220 | | - </p> |
221 | 195 |
|
222 | | - <program xml:id="file-read-exp3" interactive="activecode" language="python" add-files="my-file"> |
| 196 | + <program xml:id="file-read-py" interactive="activecode" language="python" add-files="myfile-read"> |
223 | 197 | <code> |
224 | | - with open("myfile.txt", "r") as file_reader: |
225 | | - for line in file_reader: |
226 | | - print(line.strip()) |
| 198 | + filename = "myfile.txt" |
| 199 | + try: |
| 200 | + # Attempt to open the file in read mode ('r') |
| 201 | + with open(filename, "r") as file_reader: |
| 202 | + # Iterate over each line in the file |
| 203 | + for line in file_reader: |
| 204 | + print(line.strip()) |
| 205 | + except: |
| 206 | + #catches if the file doesn't exist or can't be written to |
| 207 | + print("file could not be opened") |
227 | 208 | </code> |
228 | 209 | </program> |
229 | 210 |
|
230 | 211 | <p> |
231 | | - The equivalent Java code: |
| 212 | + 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. |
232 | 213 | </p> |
233 | 214 |
|
234 | | - <program xml:id="file-read-exp4" interactive="activecode" language="java" add-files= "my-file"> |
| 215 | + <program xml:id="file-read-java" interactive="activecode" language="java" add-files= "myfile-read"> |
235 | 216 | <code> |
236 | 217 | import java.io.File; |
237 | 218 | import java.io.FileNotFoundException; |
|
251 | 232 | } |
252 | 233 | </code> |
253 | 234 | </program> |
254 | | - |
255 | | - <p> |
256 | | - The <c>hasNextLine()</c> method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called <c>data</c> is used to store the current line that the Scanner object is pointing to. The <c>nextLine()</c> method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the <c>close()</c> method accomplishes and holds the same importance as in the section on writing to files. |
257 | | - </p> |
258 | | - |
259 | | - <p> |
260 | | - Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: |
261 | | - </p> |
262 | | - |
263 | | - <program xml:id="file-read-exp5" interactive="activecode" language="java" add-files="my-file"> |
264 | | - <code> |
265 | | - import java.io.File; |
266 | | - import java.io.FileNotFoundException; |
267 | | - import java.util.Scanner;public class Main { |
268 | | - public static void main(String[] args) { |
269 | | - String filename = "myfile.txt"; |
270 | | - try (Scanner fileReader = new Scanner(new File(filename))) { |
271 | | - String data = ""; |
272 | | - while (fileReader.hasNextLine()) { |
273 | | - data = data + fileReader.nextLine() + System.lineSeparator(); |
274 | | - } |
275 | | - System.out.println(data); |
276 | | - } |
277 | | - catch (FileNotFoundException e) { |
278 | | - System.out.println("Error: The file '" + filename + "' was not found."); |
279 | | - } |
280 | | - } |
281 | | - } |
282 | | - </code> |
283 | | - </program> |
284 | | - |
285 | | - <note> |
286 | | - <p> |
287 | | - Pay close attention to the details of this code. <c>data</c> must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning <c>data</c> in the while loop. <c>data</c> is concatinated (to ensure all lines are included) with <c>fileReader.nextLine()</c> and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. |
288 | | - </p> |
289 | | - </note> |
290 | | - |
291 | | - <p> |
292 | | - Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: |
293 | | - </p> |
294 | | - |
295 | | - <program xml:id="file-read-exp6" interactive="activecode" language="python"> |
296 | | - <code> |
297 | | - try: |
298 | | - with open("myfile.txt", "r") as file_reader: |
299 | | - data = "" |
300 | | - for line in file_reader: |
301 | | - data += line # line already includes the newline character |
302 | | - print(data) |
303 | | - except FileNotFoundError: |
304 | | - print("An error occurred.") |
305 | | - import traceback |
306 | | - traceback.print_exc() |
307 | | - |
308 | | - </code> |
309 | | - </program> |
310 | | - |
311 | | - <p> |
312 | | - And the Java equivalent: |
313 | | - </p> |
314 | | - |
315 | | - <program xml:id="file-read-exp" interactive="activecode" language="java" add-files="my-file"> |
316 | | - <code> |
317 | | - import java.io.File; |
318 | | - import java.io.FileNotFoundException; |
319 | | - import java.util.Scanner; |
320 | | - |
321 | | - public class ReadFile { |
322 | | - public static void main(String[] args) { |
323 | | - try { |
324 | | - File myFile = new File("myfile.txt"); |
325 | | - Scanner fileReader = new Scanner(myFile); |
326 | | - String data = ""; |
327 | | - while (fileReader.hasNextLine()) { |
328 | | - data = data + fileReader.nextLine() + System.lineSeparator(); |
329 | | - } |
330 | | - System.out.println(data); |
331 | | - fileReader.close(); |
332 | | - } catch (FileNotFoundException e) { |
333 | | - System.out.println("An error occurred."); |
334 | | - e.printStackTrace(); |
335 | | - } |
336 | | - } |
337 | | - } |
338 | | - </code> |
339 | | - </program> |
340 | 235 | <p> |
341 | | - In this code, we simply print the contents of the file to the console, but it is easy to imagine how the <c>data</c> variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. |
| 236 | + 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. |
342 | 237 | </p> |
343 | 238 | </section> |
344 | 239 |
|
345 | | - <section xml:id="file-write"> |
| 240 | + <section xml:id="writing-to-files"> |
346 | 241 | <title>Writing to Files</title> |
347 | 242 |
|
348 | 243 | <p> |
|
0 commit comments