Reading a text file

Now that we know how to write a text file, let’s try reading one. The following code implements the Unix cat utility in Java. That is it accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.

// Imitate the Unix cat utility

import java.io.*;

class cat {

public static void main (String args[]) {

String thisLine;

//Loop across the arguments
for (int i=0; i < args.length; i++) {

//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args[i]);

// now turn the FileInputStream into a DataInputStream
try {
DataInputStream myInput = new DataInputStream(fin);

try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println(”Error: ” + e);
}
} // end try
catch (Exception e) {
System.out.println(”Error: ” + e);
}

} // end try
catch (Exception e) {
System.out.println(”failed to open file ” + args[i]);
System.out.println(”Error: ” + e);
}
} // for end here

} // main ends here

}

windows supplier ottawa

Comments are closed.