【问题标题】:Get file to be read from another package获取要从另一个包中读取的文件
【发布时间】:2013-05-09 13:20:38
【问题描述】:

我需要捕获一个名为 files 的包文件 我尝试使用getResourceAsStream

File file = getClass().getResourceAsStream("files/big.txt")); 

但是,不起作用。这句话转换为URL。如果在这种情况下我使用URL,我可以进行向下转换,但不起作用。

我能做些什么来解决这个问题?

【问题讨论】:

  • 究竟是什么问题?

标签: java file url packages embedded-resource


【解决方案1】:

再添加一个斜杠“/” - 如果您从另一个包访问
作为评论信息,要阅读文件,请使用 URL 的 openStream()

 URL url = getClass().getResource("/files/big.txt");
     try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String nameList;
            while ((nameList = in.readLine()) != null) {
                System.out.println(nameList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

【讨论】:

  • 我需要捕获文件来读取。在这种情况下是一个 URL,所以,不去工作。
  • 您可以从 url.openStream() 获取文件...查看编辑后的答案
【解决方案2】:

如果你想要文件对象你可以调用

fileUrl.getFile()

获取文件对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多