Java Reference
In-Depth Information
public static void printFileNotFoundMsg(String fileName) {
String workingDir = System.getProperty("user.dir");
System.out.println("Could not find the file '" +
fileName + "' in '" + workingDir + "' directory ");
}
// Closes a Closeable resource such as an input/output stream
public static void close(Closeable resource) {
if (resource != null ) {
try {
resource.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Completing the Example
Listing 7-15 illustrates the steps involved in reading the file luci1.txt . If you receive an error message indicating that
the file does not exist, it will also print the directory where it is expecting the file. You may use an absolute path of the
source file instead of a relative path by replacing the statement
String srcFile = "luci1.txt";
with
// Absolute path like c:\smith\luci1.txt on Windows or /users/smith/luci1.txt
// on UNIX. Note that you must use "c:\\smith\\luci1.txt"
// (two backslashes to escape a backslash) when you construct a string that
// contains a backslash
String srcFile = "absolute path of luci1.txt file";
By simply using luci1.txt as the data source file path, the program expects that the file is present in your current
working directory when you run the program.
Listing 7-15. Reading a Byte at a Time from a File Input Stream
// SimpleFileReading.java
package com.jdojo.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SimpleFileReading {
public static void main(String[] args) {
String dataSourceFile = "luci1.txt";
try (FileInputStream fin = new FileInputStream(dataSourceFile)) {
 
Search WWH ::




Custom Search