// Source code: fileUtils.java
import java.io.File;
import java.util.Scanner;
public class fileUtils {
public Scanner getScanner(String fn) {
File file;
Scanner sc;
Scanner ret=null; // return value
String fnin="";
boolean gotFile = true;
// if there was a file name passed in, try to open in for reading
fnin = fn;
do {
if ((fnin.length() <= 0)) {
sc = new Scanner(System.in);
System.out.print("Enter a file name: ");
fnin = sc.nextLine();
}
//else
// System.out.println("process file " + fnin + " file name length = "+ fnin.length());
try {
gotFile = false;
file = new File(fnin);
ret = new Scanner(file);
gotFile = true;
} catch (Exception ex) {
System.out.println("Unable to open input file " + fnin);
fnin=""; // force next read
}
} while (!gotFile);
return ret;
}
public static void main(String[] args) {
fileUtils a = new fileUtils();
Scanner sc = null;
if (args.length > 0) {
System.out.println("arglen = " + args.length + " " + args[0]);
sc = a.getScanner(args[0]);
}
else
sc = a.getScanner("");
sc.close(); // nothing was done to the file.
} // main
} // fileUtils
|