Search code examples
javafilepathresourcesembedded-resource

Cannot read files from resources folder


Final edit: now the code looks like this

InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey);

Original post

I have a problem when reading txt file from resources folder.

This what project structure looks like:
projStructure

When I invoke the following code

System.out.println(getClass().getClassLoader().getResource("static/master-key.txt").getPath());
File mkFile = new File(getClass().getClassLoader().getResource("static/master-key.txt").getPath());

this what happens

/D:/Dropbox/Coding/Intellij%20IDEA/TishenkoKPO/target/classes/static/master-key.txt
java.io.FileNotFoundException: 
D:\Dropbox\Coding\Intellij%20IDEA\TishenkoKPO\target\classes\static\master-key.txt (System cannot find the specified path)

I've googled alot but have no clue of why this happens

Edit 1: Part of the code rebuilt as community suggested (working with file as a resource)

InputStream is = getClass().getResourceAsStream("static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey); //successfuly outputs the first line if exists 

Edit 2: resourcepath should begin with /

InputStream is = getClass().getResourceAsStream("/static/master-key.txt");

Solution

  • InputStream is = getClass().getResourceAsStream("static/master-key.txt");
    

    This is searching for a resource relative to the package / directory of the class that is calling it. It is likely that resource can actually be found relative to the root of the application structure. To do that, add a leading /, like this.

    InputStream is = getClass().getResourceAsStream("/static/master-key.txt");