Reputation: 3009
I am trying to read a file in Java called "KFormLList.txt". It is saved in the default package along with this program, yet when I try to run it I get this error message: "Error: KFormLList.txt (The system cannot find the file specified)"
What am I doing wrong? Thanks for any help.
import java.io.*;
public class VLOCGenerater {
/**
* @param args
*/
public static void main(String[] args) {
try {
//Read the text file "KFormLList.txt"
FileInputStream fis = new FileInputStream("KFormLList.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String strLine;
int V = 0;
int LOC = 0;
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
System.out.println(strLine);
V++;
}
else {
LOC++;
}
}
System.out.println("V = " + V);
System.out.println("LOC = " + LOC);
dis.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Upvotes: 1
Views: 4528
Reputation: 94429
Try putting the text file in the root directory of your project.
The name parameter passed into the FileInputStream
constructor is the path name to the file in the file system.
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
I assumed you were using Eclipse, by default Eclipse sets the user.dir
to your the root of your project. From reading other material, Netbeans follows the same convention.
This can be tested with the following code, which should output the path to your project:
System.out.println(System.getProperty("user.dir"));
Placing the file in the root of your directory allows it to be found by the FileInputStream
.
Upvotes: 5
Reputation: 310
Either you put the file in the "root directory" of your project or provide the "absolute path" of the file as argument to FileInputStream.
Hope that helps. :).
Upvotes: 1
Reputation: 3070
If you're using NetBeans (perhaps similar for Eclipse), make sure that your file is in NetbeansProjects/YourProject/
If you have compiled your program to .jar file, put the txt to same place where .jar is.
Upvotes: 1
Reputation: 4393
This way, the program expects the file in the working folder,. i.e. where you execute java. For loading from classpath (Default package), try getResourceAsStream.
Upvotes: 0