首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文件未找到异常。资源中的文本文件

文件未找到异常。资源中的文本文件
EN

Stack Overflow用户
提问于 2022-03-11 13:42:19
回答 1查看 67关注 0票数 0

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

代码语言:javascript
复制
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();
        }
EN

回答 1

Stack Overflow用户

发布于 2022-03-11 13:57:19

new File。名字上写着:这只适用于文件。jar文件中的条目本身并不是文件。

如果你写new File,或者提到FileInputStream,你就输了。不能用来处理这些东西。

幸运的是,您可以只要求JVM从加载类文件的相同位置(无论这些类文件在何处)为您提供资源。在jar中,在目录中,通过网络实时加载并不重要。您可以在URL表单和InputStream表单中获取这些资源--任何可以处理这些资源的代码都可以用来处理‘与我的类文件所在的位置相同的资源,比如jar’。

扫描器就是其中之一:它有一个接受输入流的构造函数。那我们就这么做吧!

代码语言:javascript
复制
try (var resource = MyClassName.class.getResourceAsStream("/dictionary/dictionary.txt")) {
  Scanner s = new Scanner(resource);
  .. rest of code here
}

几个注意事项:

  • /dictionary/dictionary.txt的意思是:相对于“jar的根”。如果您想相对于类文件的包,不要从前面的斜杠开始。
  • 是一个资源,所以必须关闭它,因此,这段代码使用的是
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71439457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档