[英]Cant read files from src/main/resources folder Java 8
I have package as follows 我有如下包装
src->main->java->com->Sample.java
src->main->resources->orders.csv
and 和
src->test->java->com->SampleTest.java
src->test->resources->orders.csv
In Sample.java and SampleTest.java I have the following code 在Sample.java和SampleTest.java中,我有以下代码
String file1 = "orders.csv";
Stream<String> lines1 = Files.lines(Paths.get(file1)); // Line 1
But i don't think code on Line 1 and Line 2 work. 但是我不认为1号线和2号线的代码有效。 It does not find the file.
找不到文件。 Am i setting file1 and file2 correct?
我设置的file1和file2是否正确?
Because these are resource files, you want to use Class#getResource(String)
to search for the file relative to your class and get its absolute URL. 因为这些是资源文件,所以您想使用
Class#getResource(String)
来搜索相对于您的类的文件并获取其绝对URL。
Your Sample.java
will look like this: 您的
Sample.java
将如下所示:
String file1 = "/main/resources/orders.csv";
Stream<String> lines1 = Files.lines(Paths.get(Sample.class.getResource(file1).toURI()));
And your SampleTest.java
will look like this: 您的
SampleTest.java
将如下所示:
String file1 = "/test/resources/orders.csv";
Stream<String> lines1 = Files.lines(Paths.get(Sample.class.getResource(file1).toURI()));
Now let my explain the syntax of the string " file1
". 现在,让我解释一下字符串“
file1
”的语法。 If you look at the JavaDoc , you'll see that it says: 如果查看JavaDoc ,您会看到它说:
If the name begins with a '/' ('\/'), then the absolute name of the resource is the portion of the name following the '/'.
如果名称以'/'('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。
This basically means that the path provided, if it begins with a forward slash, is to be processed relative to your source directory. 这基本上意味着,如果提供的路径以正斜杠开头,则将相对于您的源目录进行处理。 In other words, everything after the first forwards slash is a "subpath" of your source path.
换句话说,第一个正斜杠之后的所有内容都是源路径的“子路径”。 If there was no forward slash, the JVM would search for a package called "main" in the package defined by the current class loader.
如果没有正斜杠,则JVM将在当前类装入器定义的包中搜索名为“ main”的包。 So
"/main/resources/orders.csv"
will be processed as "src/main/resources/orders.csv"
, and "/test/resources/orders.csv"
as "src/test/resources/orders.csv"
. 所以,
"/main/resources/orders.csv"
将被处理为"src/main/resources/orders.csv"
和"/test/resources/orders.csv"
作为"src/test/resources/orders.csv"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.