我正在尝试读取一个名为“KFormLList.txt”的 Java 文件。它与该程序一起保存在默认包中,但是当我尝试运行它时,我收到此错误消息:“错误:KFormLList.txt(系统找不到指定的文件)”
我做错了什么?感谢您的帮助。
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());
}
}
}
最佳答案
尝试将文本文件放在项目的根目录中。
传递给 FileInputStream
构造函数的名称参数是文件系统中文件的路径名。
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.
我假设您使用的是 Eclipse,默认情况下 Eclipse 将 user.dir
设置为项目的根目录。通过阅读其他 Material ,Netbeans 遵循相同的约定。
这可以用下面的代码进行测试,它应该输出你的项目的路径:
System.out.println(System.getProperty("user.dir"));
将文件放在目录的根目录中可以让 FileInputStream
找到它。
关于java - FileInputStream 错误 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709616/