[Java] Read the file in src / main / resources

It took a while to read the file in src / main / resources in Java, so it's a reminder.

1. Get with absolute path from root

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

2. Get relative to the classpath

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

important point

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.

Summary

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

Digression

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


Thank you for reading for me until the end. If you have any questions or deficiencies, please contact us in the comments section or [Twitter](https://twitter.com/ka2_kamaboko).

Recommended Posts

[Java] Read the file in src / main / resources
Read Java properties file in C #
Unzip the zip file in Java
What is the main method in Java?
Read xlsx file in Java with Selenium
Text file placed in resources in Java cannot be read when jarted
Read JSON in Java
Read a string in a PDF file with Java
Read Java Property file
Read the packet capture obtained by tcpdump in Java
[Java] Get the file in the jar regardless of the environment
[Java] Get the file path in the folder with List
Read binary files in Java 1
Read standard input in Java
Read binary files in Java 2
[Java] [Android] Read ini file
[Java] Integer information of characters in a text file acquired by the read () method
How to read your own YAML file (*****. Yml) in Java
Correct the character code in Java and read from the URL
Access the network interface in Java
Guess the character code in Java
Easily read text files in Java (Java 11 & Java 7)
Specify the java location in eclipse.ini
Read CSV in Java (Super CSV Annotation)
Log output to file in Java
Parsing the COTOHA API in Java
Include image resources in jar file
About file copy processing in Java
Call the super method in Java
Get the public URL of a private Flickr file in Java
Read the first 4 bytes of the Java class file and output CAFEBABE
Read items containing commas in a CSV file without splitting (Java)
Sample to read and write LibreOffice Calc fods file in Java 2021
How to get the length of an audio file in java
Change the Swagger-ui read file. (Using AWS/Docker)
Get the result of POST in Java
[Java] How to use the File class
For the time being, run the war file delivered in Java with Docker
The story of forgetting to close a file in Java and failing
Try using the Stream API in Java
Call the Windows Notification API in Java
I tried the new era in Java
Memo: [Java] If a file is in the monitored directory, process it.
[Java] Use cryptography in the standard library
Organized memo in the head (Java --Array)
What is the best file reading (Java)
Try calling the CORBA service in Java 11+
Read Felica using RC-S380 (PaSoRi) in Java
Sample program that returns the hash value of a file in Java
How to get the date in java
The story of writing Java in Emacs
Console input in Java (understanding the mechanism)
Java: Place the ResourceBundle properties file anywhere
How to read log4j configuration file in Java project summarized in jar file Memo
Sample to unzip gz file in Java
[Java8] Search the directory and get the file
Set up a Java GUI in a separate thread to keep the main
I can't remember the text file input / output in Java, so I summarized it.
Java that outputs vmg format file in eml format
Regarding the transient modifier and serialization in Java
Read the file line by line VS read at once