Java Part 5: Input And Output Operations - Our file I/O application explained (contd.)
(Page 3 of 4 )
String fileName = args[0];We create a new string object named "fileName". The value of the first index in the "args" array is assigned to the "filename" value. Remember, this will be the name of the file that our application will open for reading.
FileReader fr = new FileReader(fileName);
BufferedReader input = new BufferedReader(fr);Next, we create two new variables: "fr" and "input". The "fr" variable contains a new file stream (which is used to read the file), and "input" (which is used to access the file stream) now contains a new "BufferedReader" object.
String s = input.readLine();
while( s instanceof String ){
System.out.println(s);
s = input.readLine();
}We get the first line from the file using the "readLine" method of our "FileReader" object and store it in a new string variable, "s". The while loop tests the variable "s" to see whether it is actually an instance of a string. If it is, then its value is printed to the screen using the "System.out.println" method. We repeat this loop until the variable "s" is not an instance of a string, which would mean that we have reached the end of the file.
System.exit(0);Lastly, we use the "System.exit" method to return control to the operating system. In this case, it returns a value of zero, indicating that our application succeeded. If we wanted to indicate an error, we would return "1" with the "System.exit" method, like this:
System.exit(1);Compiling our application Before we can run our "FileIO.java" file, we need to compile it (refer to part three of this series for the full tutorial on installing the Java SDK). From the command prompt, change to the directory where you saved the "FileIO.java" file, and enter this command:
javac FileIO.javaThis will compile our ".java" file into Java byte code, which can them be executed using the Java interpreter, "java", like this:
java FileIO <filename>Simply replace <filename> with the full path and name of a file on your machine. You should just create a simple text file to test our application.
Next: Conclusion >>
More Java Articles
More By Chris Noack