[英]Why can't I get a file from resources?
Why can't I get a file from resources?为什么我无法从资源中获取文件?
URL resource = getClass().getClassLoader().getResource("input data/logic test.csv");
System.out.println("Found "+resource);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
CSVReader reader = new CSVReaderBuilder(new FileReader(resource.getFile())).withSkipLines(1).withCSVParser(parser).build();
Console output:控制台输出:
Found file:/home/alexandr/Repos/OTUS/first_home_work/target/classes/input%20data/logic%20test.csv
Exception in thread "main" java.io.FileNotFoundException: /home/alexandr/Repos/OTUS/first_home_work/target/classes/input%20data/logic%20test.csv (Нет такого файла или каталога)
There is an inherent logic problem with this line:这一行存在一个固有的逻辑问题:
CSVReader reader = new CSVReaderBuilder(
new FileReader(resource.getFile()))..
Once the CSV is part of a Jar, it will no longer be accessible as a File
object.一旦 CSV 成为 Jar 的一部分,它将不再可作为
File
对象访问。 But something like this should work directly for the URL.但是这样的事情应该直接适用于 URL。
CSVReader reader = new CSVReaderBuilder(
new InputStreamReader(resource.openStream()))..
change space for _ in directory name and file name, and working
更改目录名和文件名中 _ 的空间,并工作
This will only work while the resource is not in a Jar file.这仅在资源不在Jar 文件中时有效。
It's:它的:
try (InputStream raw = ClassThisIn.class.getResourceAsStream(""input data/logic test.csv")) {
InputStreamReader isr = new InputStreamReader(raw, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
// now use br as if it was your filereader.
}
This addresses many issues:这解决了许多问题:
getClass().getClassLoader().getResource
won't, which is why you should not do that).getClass().getClassLoader().getResource
不会,这就是为什么您不应该这样做)。我在目录名和文件名中更改了 _ 的空间,然后工作.... omg。
The answer is in your console output - the file was simply not found.答案在您的控制台输出中 - 根本找不到该文件。 I would try the same code you have written, but use a file without spaces in it - and see if the file is still not found.
我会尝试您编写的相同代码,但使用一个没有空格的文件 - 看看是否仍然找不到该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.