英文:
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("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);
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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论