read file using InputStreamReader?

Basically I have a web-app and I am trying to read youtube API client_secrets.json using InputStreamReader and assign its value to Reader.

I tried:

Reader clientSecretReader = new InputStreamReader(
            Auth.class.getResourceAsStream("/home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json"));

FYI: This file is located in an external directory an not in my eclipse resources directory.

But the above code throws a nullpointerexception even though if I try my terminal nano /home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json it opens the file in a text editor which basically Assures me that the file is in its location.

Jon Skeet
people
quotationmark

You're trying to load a file, but you're using Class.getResourceAsStream to do so. If you want to load a file, use a FileInputStream. If you want to load a resource which is accessible to a ClassLoader, use Class.getResourceAsStream or ClassLoader.getResourceAsStream. They're different use cases, and should be handled with different code.

Note that the problem here has nothing to do with Reader or InputStreamReader. It's all about how you obtain the InputStream to start with. Having said that, I would encourage you to explicitly specify the encoding to use when creating an InputStreamReader, as otherwise you'll use the platform-default encoding.

Having said all of that, if you're on a modern version of Java, I'd use Files.newBufferedReader to create a Reader for the specified Path, defaulting to UTF-8 (which is probably what you want).

people

See more on this question at Stackoverflow