Energy
Energy

Reputation: 958

get file from src/test/resources using getResourceAsStream()

file structure here

++add i want to validate json based on json schema file. I currently save json as string , and try to read json schema file(which is test.json), then validate. however, reading schema file is always null..

below code are I tried so far.

++original post.

this is my current situaction. I've tried many ways to get the file(test.json)...

like

InputStream in;
    
     

1.  in= valid.class.getResourceAsStream("/test.json"); 
2.  in = getClass().getClassLoader().getResourceAsStream("/test.json");
3.   in = Thread.currentThread().getContextClassLoader().getResourceAsStream("//test.json");
4. in=getClass().getResourceAsStream("/test.json"); 
    
5. in=ValidationUtils.class.getResourceAsStream("../resources/ds/test.json"); 
    
6. ClassLoader classLoader =  getClass().getClassLoader();
   in = classLoader.getResourceAsStream("test.json");
7.in=getClass().getResourceAsStream("/ds/test.json"); //tried just now


System.out.println("in"+in); //this is always null.

nothing.. work.. above.. please help me...

Upvotes: 0

Views: 4021

Answers (2)

Florian Albrecht
Florian Albrecht

Reputation: 2326

You can't (by default) access src/test/resources resources from code within src/main/java. All src/test/resources resources are only available for tests usually stored in src/test/java and executed during test phase (in Maven). During that phase, test code can access that resources by some (not all) of the methods you quoted in your question.

For your main classes, the resources root is src/main/resources. You should store your JSON schema file there. Test code can also access resources stored there (so no duplication needed), but not vice versa.

Upvotes: 4

Leo Aso
Leo Aso

Reputation: 12463

When getting resources, the resources folder is the root. If the file is in a subfolder, you need to include it in your path. Use

in = getClass().getResourceAsStream("/ds/test.json");

Upvotes: 0

Related Questions