No big deal really. Read my comments.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import java.util.regex.*;
/**
* >> Put this class in s file called ReadFileInDriver.java
*
*/
public class ReadFileInDriver {
public static void main(String[] args) {
if (args.length != 1)
System.err.println("Usage: java ReadFileIn <source>");
else {
// you could have passed the filepath to the constructor, so when you
// want to parse several files, then the parse result could be kept by
// different ReadFileIn objects, each identifieable by the file they have
// parsed.
ReadFileIn rIn=new ReadFileIn();
try {
rIn.readit( args[0] );
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
/**
* A program that reads an ascii, comma-delimited file
* >> put this class in a file called ReadFileIn.java,
* >> AND declare it as 'public class ReadFileIn' -> When classes share
* >> the same file then only one can be 'public'
**/
class ReadFileIn {
public ReadFileIn() {} // default constructor, does basically nothing
/**
* readit is the static method that performs the file read.
**/
public static void readit(String from_name) throws IOException {
File from_file = new File(from_name);
// does source file exist and is it readable
if (!from_file.exists())
System.out.println("no source file: " + from_name);
if (!from_file.isFile())
System.out.println("unable to read directory: " + from_name);
if (!from_file.canRead())
System.out.println("source file is unreadable: " + from_name);
// read all lines from the file
//first create a FileReader Object
// then create a BufferedReader so we can use the readLine() method
// could have done it with one line : BufferedReader in = new BufferedReader(new FileReader(from_name));
try {
FileReader filer = new FileReader(from_name);
BufferedReader reader = new BufferedReader(filer);
int count = 0;
int blanks = 0;
String line = null;
// read a line of text, assign it to line variable, while not null
// loop
while ( (line = reader.readLine()) != null) {
System.out.println(line);
count++;
if (line.equals("")) {
blanks++;
}
String[] fieldArray = line.split(",");
for (int i = 0; i < fieldArray.length; ++i) {
System.out.println(fieldArray[i]);
}
}
reader.close();
System.out.println("lines: " + count + " blank lines: " + blanks);
}
catch (IOException except) {
except.printStackTrace();
}
}
}
Bookmarks