简体   繁体   中英

Unable to fetch Json file from separate project in Eclipse

I have a java application that I wants to load JSON into. The API method I'm invoking takes a InputReader so I tried the following code below:

ClassLoader classLoader = Assets.class.getClassLoader();
new InputStreamReader(classLoader.getResourceAsStream("data/clientJson.json")));

The file is in the Assets package under the ' data ' folder and yet the InputStreamReader always throws an exception stating that the input is Null .

If I move the file next to the class and change the Classloader to reference the same class it works, but not with the Assets class.

I've tried every permutation of the name path as well to no avail.

If your other Eclipse project is imported and if the data/ folder is under the src/ folder (or otherwise marked in the other project as a classpath resource), then it will work. I think you first need to verify if the Eclipse import/export relationship and the other folders classpath is correct.

样本2在Eclipse中进行项目设置

If you go to the asset (A in my example) project's properties the resources/ folder must be under "Order and Export". You can add it under "Libraries" as "Class path folder". And the Assets project must be "required projects on the build path". Note the "classpath folder" icon on A/src/main/resources.

Try

new InputStreamReader(getClass().getClassLoader().getResource("data/clientJson.json"));

EDIT:

static URL from http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

       getSystemResource(String name)
      //Find a resource of the specified name from the search path used to load classes.

BTW I always use .getInputStream(); ex:

  BufferedReader stream = new BufferedReader(new  InputStreamReader(new FileInputStream(object.getInputStream()));

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