read a file

I would like to read a flat file on the unix system. However, I got this error when running the java:

$ java ReadFile fs_sample

Exception in thread "main" java.lang.NoClassDefFoundError: ReadFile

Can anyone help me? Thanks a lot in advance.

Here is theReadFile.java:

import java.io.*;

public class ReadFile {

public static void main (String [] args) {

//create a file

File file = new File(args[0]);

System.out.println("Filename is " + args[0]);

try {

//create a buffered reader to read each line from a file.

BufferedReader in = new BufferedReader(new FileReader(file));

String s;

//read each line from the file

s=in.readLine();

while (s != null) {

System.out.println("Read: " +s);

s=in.readLine();

}

//close the buffered reader

in.close();

}

catch (FileNotFoundException el) {

//if the file does not exist

System.out.println("File not found: "+file);

}

catch (IOException e2) {

//catch other IO errors

e2.printStackTrace();

}

}

}

[1159 byte] By [AmyGa] at [2007-10-3 3:30:09]
# 1
did you compiled it?
lfschucka at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 2
yes, no errors when I compiled. And I seeReadFile.class file
AmyGa at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 3
any idea? This really puzzles me .
AmyGa at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 4

You probably have a classpath set which is incorrect.

Instead of the following (which uses the CLASSPATH environment variable):

java ReadFile fs_sample

You need something like this (if you are in the directory that contains ReadFile.class):

java -cp . ReadFile fs_sample

MLRona at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 5
Thanks, that works!So even the class is in the same directory, I still need to specify it in the CLASSPATH?
AmyGa at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 6

> Thanks, that works!

>

> So even the class is in the same directory, I still need to specify it in the CLASSPATH?

I think if you don't have a CLASSPATH environment variable, then at least some versions of java will assume the current directory (the single dot ".") as the classpath. You probably have a CLASSPATH set without your even knowing it. You can view it in the control panel, or type the following at the cmd prompt:

echo %CLASSPATH%

MLRona at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 7
got it!Thanks a lot, MLRon :)
AmyGa at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 8
You're welcome, Amy (I assume). My name is Monica. :)
MLRona at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...
# 9
Hi, You have to specify the CLASSPATH as shown belowprompt > java -cp . ReadFile myfileYou can alse set PATH variable in $home/.bashrc file as shown belowPATH=.:$PATHexport PATHBye
Fleura at 2007-7-14 21:24:00 > top of Java-index,Java Essentials,New To Java...