Java Gmail API - Reading credentials from json file using Inputstream vs BufferedReader - java

Im trying to run my java application on Ubuntu server. I enter absolute path to read that file but it produces and error.
The code which is supposed to read that file is below.
private static final String CREDENTIALS_FILE_PATH = "/home/dockeradmin/credentials.json";
InputStream in = application.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
And the error I get:
java.io.FileNotFoundException: Resource not found: /home/dockeradmin/credentials.json
When I tried to read file with same path using BufferedReader everything worked perfectly.
Like this:
BufferedReader br = new BufferedReader(new FileReader(new File("/home/dockeradmin/credentials.json")));
So my question is, what is the difference between these two and how could I solve my current problem?

The reason of the error is that getResourceAsStream is used to locate file on classpath and it can't be used for locating file on file system.

This line caused trouble.
InputStream in = application.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
I fixed this by replacing that, with that
InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);

Related

Reading a CSV file using an absolute path in java giving exception

I was trying to create a program to read a CSV file from the downloads folder on any windows computer and could not get the Java BufferedReader to find the file.
I read that java can handle absolute paths so I did:
File f = new File("%systemdrive%\\users\\%username%\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
This threw an IOException with the message :
%systemdrive%\users\%username%\Downloads\quotes.csv (The system cannot find the path specified)
I made sure that this file existed by entering the same path into File Explorer and easily enough, the file showed up.
I was wondering if something like this is possible and if there is some way to find and read this file.
Thank you for any help!
The %systemdrive% and %username% appear to be environment variables expanded by the File Explorer.
You might find this other entry in SO ( How to find out operating system drive using java? ) interesting to get the value for %systemdrive. Similarly, you can apply the same call to System.getenv to get the username.
FWIW, here there's a list of environment variables in Windows. Note the %HOMEPATH% environment variable, which points to the home directory of the current user.
With all these premises, you might consider the following code to fix your issue:
String userhome = System.getenv ("HOMEPATH");
File f = new File(userhome + "\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
You could try something like this:
String userHome = System.getProperty("user.home");
String path = userHome + "\\Downloads\\quotes.csv";
File f = new File(path);
BufferedReader br = new BufferedReader(new FileReader(f));

Load file dynamically from jar

I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.

How to load a File within a Jar that is not relative to the Class its loaded from

I am trying to load a file that is within a jar file. I try to get the file to load in a BufferedReader. For example:
BufferedReader br = new BufferedReader(new FileReader(fileName));
where fileName is my string from the root of the Jar file: something like this "resources/text.txt"
I am having a hard time finding out how to make this happen. Obviously FileReader will not work since it reads from the file system.
Anyone that can help me out?
Use the classloader to get the resource as a stream.
BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream("/resources/text.txt"), "utf-8");
Note that you need to specific the correct character encoding for the content.
If you are trying to access a file within the same jar as your running program you should use
final InputStream inputStream = ClassName.class.getResourceAsStream(fileName);

Read File in Servlets

I'm a beginner in Tomcat and Servlet.I come across a problem about reading File in servlet. I have search a lot information about this problem in stackoverflow,but I haven't solved it.I hope get some help.I write the code as following:
URL url=getServletContext().getResource("/WEB-INF/DataSpecification.owl");
File file=new File(url.toString());
FileInputStream input=new FileInputStream(file);
Reader in = new InputStreamReader(input,"UTF-8");
I get the following error:
java.io.FileNotFoundException: jndi:\localhost\MAGS\WEB-INF\DataSpecification.owl (File name or directory name wrong).
at java.io.FileInputStream.open(Native Method)
I put my file in WEB-INF directory.
I know that I can get an InputStream by using
getServletContext().getResourceAsStream()
But for some reasons,I nead to get a FileInputSream.
I hope to get your help!thank you!
This should work (no need to use FileInputStream):
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/DataSpecification.owl");
Reader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

Reading in a file - java.io.FileNotFoundException

public void loadFile(int level){
try {
//Create new file
levelFile = new File("assets/levels.txt");
fis = new FileInputStream(levelFile);
isr = new InputStreamReader(fis);
reader = new BufferedReader(isr);
//Code to read the file goes here
Using this code, however, I keep getting the above error (java.io.FileNotFoundException).
The file definitely exists in my Assets folder and has the correct name. I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using "levels.txt" instead of "assets/levels.txt" but I keep getting this error.
Any ideas why?
Because you're dealing with outside the package, getResource() will be the best solution for your problem:
URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....
Or you can directly get the input stream using getResourceAsStream() method :
InputStream is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is);
It's better since you don't have to use FileInputStream.
Note that URISyntaxException must be caught with FileNotFoundException or declared to be thrown.
In an Android project, the right way to read the content of asset files is by using the AssetManager. Asset files are the files you put in the assets/ folder of your Android project. This is mentioned briefly in the sidebar on the Accessing Resources page in the Android docs.
In particular, you can open the file assets/levels.txt and create a BufferedReader like this:
InputStream stream = context.getAssets().open("levels.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
Notice that the argument of the open call is simply levels.txt, not assets/levels.txt.
For more details see the full docs of AssetManager.

Categories