Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions source/ch8_filehandling.ptx
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,11 @@ public class CreateFile {
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 <xref ref="file-read-python" text="type-global"/> that reads each line of <xref ref="myfile-read" text="type-global"/> and prints it to the console.
Consider <xref ref="file-read-python" text="type-global"/> that reads each line of <xref ref="listing-myfile-read" text="type-global"/> and prints it to the console.
</p>
<data xml:id="myfile-read">
<data xml:id="listing-myfile-read">
<title>Data file for reading example</title>
<datafile label="myfile-read" filename="myfile.txt" editable="no">
<datafile xml:id= "myfile-read" label="myfile-read" filename="myfile.txt" editable="no">
<pre>
1
2
Expand Down Expand Up @@ -208,18 +208,18 @@ public class CreateFile {
<program interactive="activecode" language="java" add-files= "myfile-read">
<code>
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileNotFoundException; // This import is necessary to handle the exception if the file is not found
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()) {
try (Scanner fileReader = new Scanner(new File(filename))) { // try to open the file and create a Scanner object
while (fileReader.hasNextLine()) { // while there is a next line in the file
String data = fileReader.nextLine();
System.out.println(data);
}
}
catch (FileNotFoundException e) {
catch (FileNotFoundException e) { // and catch the exception if the file is not found
System.out.println("Error: The file '" + filename + "' was not found.");
}
}
Expand Down