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

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

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

问题

以下是翻译好的内容:

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

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

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

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

英文:

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

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

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

  1. URL url = getClass().getResource("example.txt");
  2. Path path = Paths.get(url.toURI());
  3. byte[] byteArray = Files.readAllBytes(path);
  4. String data = new String(byteArray, StandardCharsets.UTF_8);
  5. List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
  6. 我明确地添加了字符集否则它会根据您的软件安装而变化并且资源具有已知的字符集/编码
  7. 如果路径没有以 "/" 开头则相对于 `getClass()` 的包路径如果涉及子类最好使用 `Xyz.class`或者使用绝对路径 "/example.txt"
英文:
  1. URL url = getClass(U).getResource(&quot;example.txt&quot;);
  2. Path path = Paths.get(url.toURI()):
  3. byte[] byteArray = Files.readAllBytes(path);
  4. String data = new String(byteArray, StandardCharsets.UTF_8);
  5. 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:

确定