我正在尝试读取位于dictionary.txt中的文本文件( src/main/resources ),但是我一直得到一个没有找到异常的文件。

public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (Scanner sc = new Scanner(new File("/src/main/resources/dictionary/dictionary.txt"))){ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that d
}
System.out.println("Score is "+ ReviewScore);
}
}
public static <DoesWordExist> void DoesWordExist(int ReviewScore, String s) {
// TODO Auto-generated method stub
HashSet<DoesWordExist> set = new HashSet<>();
try (var resource = Review.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner sc = new Scanner(resource);{ // Reading dictionary
if (set.contains (s)) { // Checking word is in dictionary
}
else {
ReviewScore -= 5; // each word that is not found due to either typo or non-existence deduct 5pts
}
System.out.println("Score is "+ ReviewScore);
}
//frequentlyUsedWords (ReviewScore,Review);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}发布于 2022-03-11 13:57:19
new File。名字上写着:这只适用于文件。jar文件中的条目本身并不是文件。
如果你写new File,或者提到FileInputStream,你就输了。不能用来处理这些东西。
幸运的是,您可以只要求JVM从加载类文件的相同位置(无论这些类文件在何处)为您提供资源。在jar中,在目录中,通过网络实时加载并不重要。您可以在URL表单和InputStream表单中获取这些资源--任何可以处理这些资源的代码都可以用来处理‘与我的类文件所在的位置相同的资源,比如jar’。
扫描器就是其中之一:它有一个接受输入流的构造函数。那我们就这么做吧!
try (var resource = MyClassName.class.getResourceAsStream("/dictionary/dictionary.txt")) {
Scanner s = new Scanner(resource);
.. rest of code here
}几个注意事项:
/dictionary/dictionary.txt的意思是:相对于“jar的根”。如果您想相对于类文件的包,不要从前面的斜杠开始。https://stackoverflow.com/questions/71439457
复制相似问题