|
167 | 167 | 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. |
168 | 168 | </p> |
169 | 169 | </note> |
170 | | - </section> |
171 | | - |
| 170 | + </section> |
172 | 171 |
|
173 | 172 | <section xml:id="file-read"> |
174 | 173 | <title>Reading Files</title> |
175 | 174 |
|
176 | 175 | <p> |
177 | | - 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: |
178 | | - </p> |
179 | | - <datafile label="my-file" filename="myfile.txt" xml:id= "my-file" editable="no"> |
| 176 | + 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 its content. In Java you read files in a very similar way, however in java we will use a <c>Scanner</c> object in order to iterate through lines. |
| 177 | + </p> |
| 178 | + <p> |
| 179 | + The next lines consists of a Python code example that reads each line of the file and prints it to the console. |
| 180 | + </p> |
| 181 | + <datafile label="my-file-8-3" filename="myfile.txt" xml:id= "my-file-8-3" editable="no"> |
180 | 182 | <pre> |
181 | 183 | 1 |
182 | 184 | 2 |
|
188 | 190 | 8 |
189 | 191 | </pre> |
190 | 192 | </datafile> |
191 | | - |
192 | | - |
193 | | - <program xml:id="file-read-exp1" interactive="activecode" language="java" add-files= "my-file"> |
194 | | - <code> |
195 | | - import java.io.File; |
196 | | - import java.io.FileNotFoundException; |
197 | | - import java.util.Scanner;public class Main { |
198 | | - public static void main(String[] args) { |
199 | | - try { |
200 | | - File myFile = new File("myfile.txt"); |
201 | | - Scanner fileReader = new Scanner(myFile); |
202 | | - System.out.println("Reading from file: " + myFile.getName()); |
203 | | - while (fileReader.hasNextLine()) { |
204 | | - String data = fileReader.nextLine(); |
205 | | - System.out.println(data); |
206 | | - } |
207 | | - fileReader.close(); // Close the scanner to release the file |
208 | | - } catch (FileNotFoundException e) { |
209 | | - System.out.println("An error occurred: The file was not found."); |
210 | | - e.printStackTrace(); |
211 | | - } |
212 | | - } |
213 | | - } |
214 | | - </code> |
215 | | - </program> |
216 | | - |
217 | | - <p> |
218 | | - 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: |
219 | | - </p> |
220 | 193 |
|
221 | | - <program xml:id="file-read-exp2" interactive="activecode" language="java" add-files="my-file"> |
| 194 | + <program xml:id="file-read-exp1" interactive="activecode" language="python" add-files="my-file-8-3"> |
222 | 195 | <code> |
223 | | - import java.io.File; |
224 | | - import java.io.FileNotFoundException; |
225 | | - import java.util.Scanner; |
226 | | - public class Main { |
227 | | - public static void main(String[] args) { |
228 | | - // This 'try-with-resources' statement handles opening the file |
229 | | - // and guarantees it is closed automatically, which is best practice. |
230 | | - try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { |
231 | | - |
232 | | - // If this line is reached, the file was opened successfully. |
233 | | - System.out.println("Success! The file 'myfile.txt' is now open."); |
234 | | - |
235 | | - } catch (FileNotFoundException e) { |
236 | | - |
237 | | - // This block runs only if 'myfile.txt' does not exist. |
238 | | - System.out.println("Error: The file 'myfile.txt' could not be found."); |
239 | | - } |
240 | | - } |
241 | | - } |
242 | | - </code> |
243 | | - </program> |
244 | | - |
245 | | - <p> |
246 | | - The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.: |
247 | | - </p> |
248 | | - |
249 | | - <program xml:id="file-read-exp3" interactive="activecode" language="python" add-files="my-file"> |
250 | | - <code> |
251 | | - with open("myfile.txt", "r") as file_reader: |
252 | | - for line in file_reader: |
253 | | - print(line.strip()) |
| 196 | + filename = "myfile.txt" |
| 197 | + try: |
| 198 | + # Attempt to open the file in read mode ('r') |
| 199 | + with open(filename, "r") as file_reader: |
| 200 | + # Iterate over each line in the file |
| 201 | + for line in file_reader: |
| 202 | + print(line.strip()) |
| 203 | + except: |
| 204 | + #catches if the file doesn't exist or can't be written to |
| 205 | + print("file could not be opened") |
254 | 206 | </code> |
255 | 207 | </program> |
256 | 208 |
|
257 | 209 | <p> |
258 | | - The equivalent Java code: |
| 210 | + 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. |
259 | 211 | </p> |
260 | 212 |
|
261 | | - <program xml:id="file-read-exp4" interactive="activecode" language="java" add-files= "my-file"> |
| 213 | + <program xml:id="file-read-exp2" interactive="activecode" language="java" add-files= "my-file-8-3"> |
262 | 214 | <code> |
263 | 215 | import java.io.File; |
264 | 216 | import java.io.FileNotFoundException; |
|
278 | 230 | } |
279 | 231 | </code> |
280 | 232 | </program> |
281 | | - |
282 | | - <p> |
283 | | - 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. |
284 | | - </p> |
285 | | - |
286 | | - <p> |
287 | | - Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: |
288 | | - </p> |
289 | | - |
290 | | - <program xml:id="file-read-exp5" interactive="activecode" language="java" add-files="my-file"> |
291 | | - <code> |
292 | | - import java.io.File; |
293 | | - import java.io.FileNotFoundException; |
294 | | - import java.util.Scanner;public class Main { |
295 | | - public static void main(String[] args) { |
296 | | - String filename = "myfile.txt"; |
297 | | - try (Scanner fileReader = new Scanner(new File(filename))) { |
298 | | - String data = ""; |
299 | | - while (fileReader.hasNextLine()) { |
300 | | - data = data + fileReader.nextLine() + System.lineSeparator(); |
301 | | - } |
302 | | - System.out.println(data); |
303 | | - } |
304 | | - catch (FileNotFoundException e) { |
305 | | - System.out.println("Error: The file '" + filename + "' was not found."); |
306 | | - } |
307 | | - } |
308 | | - } |
309 | | - </code> |
310 | | - </program> |
311 | | - |
312 | | - <note> |
313 | | - <p> |
314 | | - 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. |
315 | | - </p> |
316 | | - </note> |
317 | | - |
318 | | - <p> |
319 | | - 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: |
320 | | - </p> |
321 | | - |
322 | | - <program xml:id="file-read-exp6" interactive="activecode" language="python"> |
323 | | - <code> |
324 | | - try: |
325 | | - with open("myfile.txt", "r") as file_reader: |
326 | | - data = "" |
327 | | - for line in file_reader: |
328 | | - data += line # line already includes the newline character |
329 | | - print(data) |
330 | | - except FileNotFoundError: |
331 | | - print("An error occurred.") |
332 | | - import traceback |
333 | | - traceback.print_exc() |
334 | | - |
335 | | - </code> |
336 | | - </program> |
337 | | - |
338 | | - <p> |
339 | | - And the Java equivalent: |
340 | | - </p> |
341 | | - |
342 | | - <program xml:id="file-read-exp" interactive="activecode" language="java" add-files="my-file"> |
343 | | - <code> |
344 | | - import java.io.File; |
345 | | - import java.io.FileNotFoundException; |
346 | | - import java.util.Scanner; |
347 | | - |
348 | | - public class ReadFile { |
349 | | - public static void main(String[] args) { |
350 | | - try { |
351 | | - File myFile = new File("myfile.txt"); |
352 | | - Scanner fileReader = new Scanner(myFile); |
353 | | - String data = ""; |
354 | | - while (fileReader.hasNextLine()) { |
355 | | - data = data + fileReader.nextLine() + System.lineSeparator(); |
356 | | - } |
357 | | - System.out.println(data); |
358 | | - fileReader.close(); |
359 | | - } catch (FileNotFoundException e) { |
360 | | - System.out.println("An error occurred."); |
361 | | - e.printStackTrace(); |
362 | | - } |
363 | | - } |
364 | | - } |
365 | | - </code> |
366 | | - </program> |
367 | 233 | <p> |
368 | | - 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. |
| 234 | + 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 false 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. |
369 | 235 | </p> |
370 | 236 | </section> |
371 | 237 |
|
|
0 commit comments