It took a while to read the file in src / main / resources
in Java, so it's a reminder.
src/main/resources/sample1.txt
sample1
src/main/java/Foo.java
public void sample1() {
String path = "src/main/resources/sample1.txt";
try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
Execution result
sample1
src/main/resources/sample2.txt
sample2
src/main/java/Foo.java
public void sample2() {
String path = "/sample2.txt";
//Foo for static methods.class.Write like getResourceAsStream(Foo is the class name)
try (InputStream is = getClass().getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
Execution result
sample2
In 1 and 2, when testing, the behavior when there is a file with the same name in src / test / resources
is different.
src/test/resources/sample1.txt
test1
src/test/resources/sample2.txt
test2
src/test/java/FooTest.java
public class FooTest {
@Test
public void testInput() throws Exception {
Foo foo = new Foo();
foo.sample1(); // src/main/resources/sample1.Read txt
foo.sample2(); // src/test/resources/sample2.Read txt
}
}
Execution result
sample1
test2
In the case of 1, it is natural because the path is written directly, but sample1.txt
under the src / main / resources
directory is read.
In case of 2, sample2.txt
under the src / test / resources
directory is read in preference to src / main / resources
.
If there is no sample2.txt
in the src / test / resources
directory, sample2.txt
under the src / main / resources
directory will be read as it is.
Should I use Class # getResourceAsStream
for the time being?
I would appreciate it if you could let me know if you have any problems.
reference: Getting resources [Java] Difference in how to get files on the classpath
When I got the absolute path via Class # getResource
instead of Class # getResourceAsStream
and passed it to Paths # get
, I got java.nio.file.InvalidPathException
.
String filename= "/sample2.txt";
String filepath = getClass().getResource(filename).getPath();
Path path = Paths.get(filepath); // java.nio.file.InvalidPathException
It seems that the drive letter part needs to be escaped in the Windows environment, and I was able to get it by replacing it as follows.
String filename= "/sample2.txt";
String filepath = getClass().getResource(filename).getPath();
Path path = Paths.get(filepath .replaceFirst("^/(.:/)", "$1")); // OK
Reference: create Java NIO file path problem
Recommended Posts