Java无法访问src/main/resources中的txt文件。

huangapple go评论77阅读模式
英文:

Java can't access txt file in src/main/resources

问题

以下是翻译好的内容:

我正在尝试使用getClass.getResourcesAsStream()获取我的txt文件,但是它不起作用。代码如下。

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    InputStream inputStream = getClass().getResourceAsStream("example.txt");
    byte[] byteArray = inputStream.readAllBytes();
    String data = new String(byteArray, StandardCharsets.UTF_8);
    String[] stringArray = data.split("\r\n");
    System.out.println(stringArray.length + "行");
}

我得到了一个异常,说没有找到适合的构造函数以便用InputStream来初始化File。

我不知道如何修复这个问题并使其正常工作。

英文:

I'm trying to get my txt file with getClass.getResourcesAsStream(), but it is not working. The code is below.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        File file = new File(getClass().getResourceAsStream("example.txt"));
        FileInputStream fis = new FileInputStream(file);
        byte[] byteArray = new byte[(int)file.length()];
        fis.read(byteArray);
        String data = new String(byteArray);
        String[] stringArray = data.split("\r\n");
        System.out.println(stringArray.length+" lines");
    }

I am getting an exception that says no suitable constructor found for File(InputStream)

I don't know how to fix this and make it functional.

答案1

得分: 1

URL url = getClass().getResource("example.txt");
Path path = Paths.get(url.toURI());
byte[] byteArray = Files.readAllBytes(path);
String data = new String(byteArray, StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

我明确地添加了字符集否则它会根据您的软件安装而变化并且资源具有已知的字符集/编码

如果路径没有以 "/" 开头则相对于 `getClass()` 的包路径如果涉及子类最好使用 `Xyz.class`。或者使用绝对路径 "/example.txt"
英文:
URL url = getClass(U).getResource(&quot;example.txt&quot;);
Path path = Paths.get(url.toURI()):
byte[] byteArray = Files.readAllBytes(path);
String data = new String(byteArray, StandardCharsets.UTF_8);
List&lt;String&gt; lines = Files.readAllLines(path, StandardCharsets.UTF_8);

I explicitly added the Charset, as otherwise it varies per installation of your software, and a resource has a known charset/encoding.

The path is relative to the package path of getClass() if not preceded by "/". It might be better to use Xyz.class instead - in case of a child class. Or use an absolute path "/example.txt".

huangapple
  • 本文由 发表于 2020年9月24日 19:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64045980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定