java eclipse项目如何在运行时搜索外部资源(如txt文件)?我的代码出错了
我对此主题有疑问,请参见以下内容:
我在eclipse子目录“resources”中有2个txt文件,如下所示:
我试图将它们的名称以及它们的内容传递给一个类,该类将返回它们所包含的行数
请参见我的主要课程:
public static void main(String[] args) throws IOException {
int num_words = FileLineCount.countLines("Lexicon.txt");
System.out.println("NUmber of lines: " + num_words);
}
和我的文件行计数类:
public class FileLineCount {
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
}
运行此程序时,出现以下错误:
Exception in thread "main" java.io.FileNotFoundException: Lexicon.txt (No such file or directory)
这是因为我的txt文件位于子目录中吗?eclipse java程序如何在运行时搜索外部资源(如txt文件)
# 1 楼答案
我不知道如何使用纯eclipse项目。但我创建了一个具有以下目录结构的eclipse Java项目:
然后我创建了以下子文件夹,如下所示:
我在
main
文件夹中创建了一个类,比如TestFileResource
,其中包含main()
方法。在main()
方法中,我做了以下修改:最后,我在
countLines()
方法内部做了以下修改:通过这个小小的修改,程序可以运行并读取输入文件
实际上,我不确定程序是否正确,因为我在文件
Lexicon.txt
中添加了以下行:那么程序的输出是:
希望这能给你一个解决问题的方法
我最后的建议是:尝试使用一些构建工具,而不是创建eclipse项目:-)
在这里,您可以找到
getResourceAsStream()
方法的JavaDoc以了解更多信息: https://docs.oracle.com/javase/7/docs/api/index.html?java/lang/ClassLoader.html