【问题标题】:read file from resource Java [duplicate]从资源Java中读取文件[重复]
【发布时间】:2020-08-14 04:10:44
【问题描述】:

我发现这个文件存在于显示的 url 中,但仍然得到 NoSuchFileException。 尝试了很多方法,但路径返回始终相同,但无法读取文件。会怎样?它在那里但不在那里?为什么?

 public void readFile() throws IOException {
  
    String fileName = "domain.txt";
    ClassLoader classLoader = getClass().getClassLoader();

    File file = new File(classLoader.getResource(fileName).getFile());

    //File is found
    System.out.println("File Found : " + file.exists());

    //Read File Content
    String content = new String(Files.readAllBytes(file.toPath()));
    System.out.println(content);
}

【问题讨论】:

  • 你有没有尝试过这样的事情:stackoverflow.com/questions/3888226/…?而且,顺便说一句,您永远不应该将您的代码作为图片发布。将代码和输出粘贴到问题本身,以便我们复制它。
  • 资源不是文件。您需要使用Class.getResource() 和朋友,而不是文件。请勿在此处发布文字图片。发布文本。
  • @MarquisofLorne 抱歉,我已经编辑过了。但是当我使用 Class classer = getClass(); URL url = class.getResource("domain.txt");我得到空
  • 不要调用getFile(),或者创建File,或者其他的。 ClassLoader.getResource() 返回一个URL:直接从中获取输入流。

标签: java file


【解决方案1】:

使用 ClassLoader 时必须使用绝对路径

public void readFile() throws IOException {

    // Must use absolute path here, so start with a slash
    String fileName = "/domain.txt";

    // Use InputStream instead of File
    InputStream input = ClassLoader.getSystemResourceAsStream(filename);
    BufferedReader bf = new BufferedReader(new InputStreamReader(input));

    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = bf.readLine()) != null) {
        sb.append(line);
    }

    System.out.println(sb.toString());

    System.out.println(content);
}

【讨论】:

  • @Downvoter 请解释一下。这个答案是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 2019-08-19
  • 2020-01-20
  • 2010-09-29
相关资源
最近更新 更多