Reading a resource with BufferedReader - java

I am trying to read a resource that will be included into a .JAR, but I get a nullPointer
for the following:
bReader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("resources/" + fileName)));
Using a File however, works fine..
bReader = new BufferedReader(new FileReader(new File("resources/" + fileName)));

Assuming your IDE/Maven/ANT/Gradle/build process will include contents of "resources" in jar at root, try finding it at "/".
bReader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("/" + fileName)));
UPDATE:
Make sure the "resources" folder is configured as a resource folder.

Is this a Spring framework project? Try:
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new ClassPathResource("XML_Request.xml").getInputStream()));
Resource to load is sitting in the src/main/resources directory:

Set "resources" folder as a resource folder.
Try this code:
bReader = new BufferedReader(new
InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))

Unlike getClassLoader().getResourceAsStream(filename), the version you are using getClass().getResourceAsStream(filename) uses a path relative to the class's location, rather than the classpath root. You need to either use an absolute path getClass().getResourceAsStream("/" + filename) or use the ClassLoader version.
Also, make sure "resources" is on your classpath (if you are using Maven, it should be "src/main/resources" relative to your pom.xml). If so, you don't need to actually include "resources" in your filename, because that is the classpath root.

This is because of the reader class and the file to be read are in different packages. When this.getClass().getRasourceAsStream("resource/file_name") is called, it will search for the resource directory in the package directory where the current reader class presents if found then it will search for "file_name" file. So, if your file is not present it returns null.
In this case, you need to come back from current file reader class directory accordingly and then you have to give the path to your file. To back from a directory we should use ../
For example, if
Reader class package : package com.abc.util;
File present in : com.abc.template;
Then you should call the getResourceAsStream() method as follows.
bReader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("../template/" + fileName)));

this.getClass().getResourceAsStream("resources/" + fileName) loads file from classpath as new File("resources/" + fileName) loads file from your work dir(the project root dir in eclipse). To make the former work, you need to add the jar which containing resources dir to your classpath.

Related

How to read a file that i created inside my the same package?

This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);

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

How to link a local file

I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post

Opening a resource file in a servlet on Openshift

I'm in troubles with opening file within my web-app. I tried it locally within Eclipse and it works fine but when I try to deploy it on Tomcat 6 on Openshift it doesn't find resource files for my web-app. There are some txt files in a ProjectFiles directory stored in WEB-INF directory; the code that locally opens file is
String nome_file = "C\:\\Users\\miKKo\\workspace\\fantacalcio_project\\WebContent\\WEB-INF\\ProjectFiles\\Risultati\\risultati_" + nome_lega + ".txt";
BufferedReader reader = new BufferedReader(new FileReader(nome_file));
I've pushed them within Git in the same repository (on server I renamed my project in "ROOT") and I've substituted string with this
String nome_file = this.getServletConfig().getServletContext().getContextPath()+"/WebContent/WEB-INF/ProjectFiles/Risultati/risultati_" + nome_lega + ".txt";
but it doesn't work. I've also tried with a context attribute
/var/lib/openshift/51c6178a5004467630000019/jbossews/work/Catalina/localhost/_/WEB-INF/ProjectFiles
but the thrown exception is always
java.io.FileNotFoundException: (#path) (No such file or directory)
What can I do for this?
Say your file is in the following location:
/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt
Then using:
String path = "/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt";
InputStream inputStream = new FileInputStream(this.getServletConfig().getServletContext().getRealPath(path));
Should work for you. Note that, ServletContext.getRealPath() return the real OS path corresponding to the given virtual path.
Edit:
If this doesn't work for your case, you really need to revisit your virtual path. You can manually check that does this file exist in the expected directory in the war file or you can log the output of the getRealPath() method to examine what's really going on! If necessary you can put "/" in your getRealPath() method and examine what is your application's root path.
Since I don't get application's root realpath, I resolved in this way:
String path="/WEB-INF/ProjectFiles/Risultati/risultati_test.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
and now it works. By the way, I also found useful informations here
getResourceAsStream() vs FileInputStream

placing a input file relative to program

In my program (simple plain cosole app) I am reading a file a.txt.
Now I will be giving the program to someone else and he should be able to run it. I don't want the file path to be fixed like D:\a.txt , instead it should be relative to my program. Where should I place the file so that my program always finds it?
File file = new File("D:\aks.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while( (str= bufferedReader.readLine())!=null){
}
My code is working fine when I hard code the path like D:\a.txt
Put the file in the classpath (e.g. the package root or in a certain package) and just get it straight from the classpath as follows
InputStream input = getClass().getResourceAsStream("/a.txt");
// ... (continue with InputStreamReader and so on)
(the exact path depends on the location of the current class and whether you prefix with / to start from package root and which classloader you're using)
Package and distribute it as a single executabele JAR file.
See also:
Java: Pathnames not working once I export to JAR

Categories