0
InputStream inputStream = new FileInputStream(new File(this.getClass().getResource("/example.txt").getFile()))

This method will cause error like as "/.../.../...jar!/example.txt (no such file or directory)" .

InputStream inputStream = getClass().getResourceAsStream("/example.txt")

This method will run right.

So, what's the difference between those two methods? And why the first method does't work?

formath
  • 319
  • 3
  • 17
  • 1
    Check this link http://stackoverflow.com/questions/14089146/file-loading-by-getclass-getresource. Maybe this will help you. – CrazyJavaLearner Jun 27 '16 at 04:51
  • 1
    Good answer. That solved my puzzle. Thank you. – formath Jun 27 '16 at 05:03
  • "If you package your app into a jar file, or if you load the classes over a network, it won't work." I just know this does't work but still don't know why not work. Can you explain more? @Dharani – formath Jun 29 '16 at 02:50

1 Answers1

0

getResources will return your application resources. These are essentially resources that are present with your application at compile time and are bundled into your application. These resources are readonly. In order to modify them you have to copy them into somewhere else(preferably into your application private documents directory).

getResourceAsStream will give you an input stream for any given resource. This an be your application bundled resources(discussed above) or can be created dynamically. Keep in mind that in order to use getResourceAsStream you must have access to given resource.

Khurram Shehzad
  • 261
  • 3
  • 12