|
// Give the length in bytes of a text file
// passed as a command line argument.
// Use a FileReader to count the bytes directly
// and compare to the File.length() method.
//
// Adapted from exfileread.java from
// "Just Java", P.van der Linden, ch.12
//
import java.io.*;
public class
TextFileInput {
public
static void main(String args[]) {
int i=0;
int bytesRead=0;
File f = new File(args[0]);
if( !f.exists() ) {
System.out.println("No such file");
System.exit(0);
}
// Read the bytes directly and count them.
try {
FileReader fr = new FileReader(
f );
while ( i != -1 ) {
i = fr.read();
if (i!=-1) bytesRead++;
}
} catch (IOException ioe) {
System.out.println( "IO error:" + ioe );
}
System.out.println("bytes read from file: "+bytesRead);
//
Use the File class length() to provide the number
// of bytes to compare.
System.out.println("bytes in File.length():
"+f.length() );
}
}
|