Java getting file as resource when it's in the project folder - java

I currently have a project in Java set up with the following directory structure in Eclipse:
And in my code I have the following lines:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
However, the InputStream is always gets assigned to null, which causes a crash when it gets to the second line. I know it has something to do with how I set up the path that it's looking for, but I can't figure out exactly why it isn't working.

Your config file is in your project, somewhere on the file system.
However, Eclipse isn't putting it on the classpath. To force it to be on the classpath, right click your folder and add it as a source folder. Eclipse will then add it to the root of the classpath. You can retrieve it with
InputStream is = this.getClass().getResourceAsStream("/config");
Eclipse puts everything in resources source folder starting at the root of the classpath. Therefore
resources/config
will appear in classpath as
/config
/qbooksprintfix/FileChecker
/qbooksprintfxi/FilePurgeHandler
/...

Try whit InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();
or InputStream is = this.getClass().getClassLoader().getResourceAsStream("/resources/config");
In both cases make sure to put "/" before the "resources"

Related

resources folder is not getting found in eclipse with InputStream in = getClass().getResourceAsStream("resources/template.properties");

I have an awt application which will be run using executable JAR file. Few Issues I am facing in getting resources folder
1. In Eclipse, If I use following code
properties = new Properties();
InputStream in =getClass().getResourceAsStream("resources/template.properties");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Then I am getting
ERROR 2019-11-11 12:03:44,052 [AWT-EventQueue-0]
java.lang.NullPointerException
If I use the above code in eclipse and when I export runnable Jar then it is working in JAR file but when I run in eclipse it is throwing nullpointer exception.
Case 2: But if I use below code and export JAR file then JAR file is throwing error as "in current directory resources is not available" even resources folder is present.
properties = new Properties();
InputStream in =
inputStream = new FileInputStream("resources/template.properties");
Folder structure
enter image description here
You shouldn't reference the resource folder in the file path string. But then, your resource folder needs to be a source folder for Eclipse.
I don't know your project strcuture yet, but I suggest you to create a resource folder on your project root, then rigth click on it and go to Build Path > Use As a Source Folder.
After that, all files inside that folder will both be directly accessed by the getResourceAsStream method, and also be placed on the JAR root, merged with all other files from the other source folders.
Then you can do:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template.properties");
This way should work both inside Eclipse and in the standalone JAR.
PS: I strongly suggest you to start using Maven projects and follow its folder structure.
You don't need to specify the resources path if you do like this snippet bellow it might work.
InputStream inputStream = getClass()
.getClassLoader().getResourceAsStream("template.properties");

Reading from file in Eclipse plugin

I need to read the configuration details from a properties file in eclipse. I have put the config.properties at the same level as plugin.xml and in the class file I call:
Properties properties = new Properties();
FileInputStream file;
String path = "./config.properties";
file = new FileInputStream(path);
properties.load(file);
I get a file not found exception. Is there a better way of doing this?
Did you remember to include it in the build?
Secondly, using the classloader resource is probably better anyway
InputStream fileStream = myClass.getResourceAsStream( "/config.properties" );
Also, there is another way of opening a resource URL in eclipse using
url = new URL("platform:/plugin/com.example.plugin/config.properties");
InputStream inputStream = url.openConnection().getInputStream();
Put the properties file in the root of your project. This should be where the user.dir system property is pointing. The FileInputStream constructor looks in this directory for the file.
You can confirm it is in the correct directory by outputting the System Property.
System.getProperty("user.dir");
If it is a plugin, you should tell it that your file must be included into the target. It is set in the build.properties file. Open it and look - you haven't your file mentioned there.
Open plugin.xml, go to build tab and include your file in the binary.build by checking it. Save. That will change the build.properties file correctly. Go to build.properties tab and look at the file again - now you see your file included correctly.
Of course, you could do it by hand, but plugin UI is convenient and you can be sure you haven't any problem ends of line or spaces.
For absolute addressing the files in the plugins look here

File path errors in eclipse? (Java Spring)

InputStream inp = new FileInputStream("src/main/resources/ExportHour.xls");
I have a file in the src/main/resources folder of my Java Spring project.
I am attempting to create an inputstream in one of my Controllers, however I always get a file not found exception. When I change the path location to point specifically to the file on my machine, it works fine.
Any way I can make it so the file can be found within the java project?
Try with spring ClassPathResource.
InputStream inp = new ClassPathResource("ExportHour.xls").getInputStream();
That is because the resources folder in maven is put in your jar file directly i.e. the ExportHours.xls file is put inside your jar in the root directory.
It sounds like you could just change the working directory of your process - it's not where you think it is, I suspect. For example, I suggest you write
File file = new File("src/main/resources/ExportHour.xls");
and then log file.getAbsolutePath(), to see what exact file it's using.
However, you should almost certainly not be using a FileInputStream anyway. It would be better to use something like:
InputStream inp = Foo.class.getResourceAsStream("/ExportHour.xls");
... for some class Foo which has a classloader which includes the resources you need.
(Or possibly /resources/ExportHour.xls", depending on your build structure.)
That way even when you've built all of this into a jar file, you'll still be able to open the resource.

Where to place a file within a Java Web Project?

I have a small java program that reads a file in, in eclipse i have the file in the main project dir and the class file is within the src dir. This works fine.
I want to you this small piece of code within a web project im working on, currently i have the class file in src/tools/, but im lost on where to put the file?
I have tried it in a few places yet it throws file not found.
Where is the best place to store this file? and how can i ensure i have the right path when using the following code?
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
You either need to load the file as a resource (e.g., getResourceAsStream(), use a path relative to the app (getRealPath()), or put it in an absolute location and use a full path.
If you put the resource file in the root of your classpath (so if your source path for java files is src/main/java then put the resource file in there) then you can do this.
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("myresource.txt")));
Now if you want you can put it in a package, so the file would be in src/main/java/com/sksamuel
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("com/sksamuel/myresource.txt")));
Finally, if you're using maven or something similar, then you would put the file into src/main/resources and not src/main/java, and at compile time the two paths are combined, so you would use the same code as above.
My answer assumes the file will be packaged up with your java code and is something that would change by a developer. If it's generated, or needs to be changed outside the jar/war then this isn't the best way.

Where does Java put resource files when I JAR my program?

Been looking for this for the past 2 hours and can't find anything (I've found solutions to the same problem but with images, not text files).
Pretty much, I made a program that reads a text file. The file is a list of names and IDs. Using Eclipse, I put the file in my src folder and in the program put the path file to it. Like this:
in = new BufferedReader(new FileReader(curDir+"\\bin\\items.txt"));
Where curDir is the user's current directory (found with System.getProperty("user.dir")).
Now, problem is, the program runs fine when I run it from Eclipse, but when I try to make it a runnable JAR and then run it, the program runs, but the info from the text file does not load. It look like Eclipse is not putting the text file with the JAR.
EDIT: Solved-ish the problem? So the JAR file needs to the in a folder with all the original files? I am so confused, what is a JAR file then?
A more robust way to get a file whether you are running from Eclipse or a JAR is to do
MyClass.getResource("items.txt")
where MyClass is a class in the same package (folder) as the resource you need.
If Eclipse is not putting the file in your JAR you can go to
Run -> Run Configurations -> -> Classpath tab -> Advanced -> Add Folders
Then add the folder containing your file to the classpath. Alternatively, export the Ant script and create a custom build script.
To the point, the FileReader can only read disk file system resources. But a JAR contains classpath resources only. You need to read it as a classpath resource. You need the ClassLoader for this.
Assuming that Foo is your class in the JAR which needs to read the resource and items.txt is put in the classpath root of the JAR, then you should read it as follows (note: leading slash needed!):
InputStream input = Foo.class.getResourceAsStream("/items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
Or if you want to be independent from the class or runtime context, then use the context class loader which operates relative to the classpath root (note: no leading slash needed!):
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
(UTF-8 is of course the charset the file is encoded with, else you may see Mojibake)
Get the location of your jar file
Firstly create a folder(say myfolder) and put your files inside it
Consider the following function
public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0]+"myfolder/";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Suppose your jar file is in D:\Test\dist
Then path() will return /D:/Test/dist/myfolder/filename
Now you can place 'myfolder' inside the folder where your jar file is residing
OR
If you want to access some read-only file inside your jar you should copy it to one
of your packages and can access it as
yourClassname.getResource("/packagename/filename.txt");

Categories

Resources