简体   繁体   中英

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...

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM