Project root folder path - java

I have a class in a package com.mwerner.utils that needs the path for an getResourceAsStream() call
the file it is supposed to load is located in a subfolder of the project root i.e.:
/src/com/mwerner/utils/myfile.java has to load
/res/file.xml
I tried stuff like
/res/file.xml
../res/file.xml
res/file.xml
What is the right one?
EDIT:
I am using Xstream to parse the XML into objects. The line of code in question is:
ObjectInputStream in = xstream.createObjectInputStream(Utils.class.getResourceAsStream("res/file.xml"));
I get an IOException with unknown source

Turns out Eclipse puts the entire content of the res folder in the root folder of the bin folder. Therefore the path is just very simply /file.xml. I tried putting it into a subfolder of res called xmls and the path then is /xmls/file.xml
I also went to the source tab of the java build path and added the res folder.

Related

Resource can not be found in src folder

I have setup a project in eclipse, which has the default src folder and a newly created source folder called rsc. Inside the rsc folder, there is an audio file called sound.wav, which I am accessing with the following code:
InputStream input = this.getClass().getClassLoader().getResourceAsStream("sound.wav");
And this works just fine, when I put it into a Clip for example I can play the sound. However, if I move the file into the src folder, the file is no longer found and the method returns null. I did try different permutations of the url like the following, but none worked.
"/sound.wav"
"src/sound.wav"
"/src/sound.wav"
When looking at the project properties under the source tab, both folders are marked as source folders and have the same settings. So the question remains, why can java only find the resource inside the rsc folder, but not inside the src folder?

JAVA - Find files located in different packages

How can i find files which are located in different packages of the same project?
My Eclipse package is organized as follow:
There are these folders:
src/main/java
input
into the folder src/main/java i have the package main which contains my Main class, while into the input folder i have an .xml file which i want to edit from the Main. My problem is how can i know the relative path of my .xml file in the input folder from my Main class?
You can use ".." in the relative path to go to the folder above for example in your case : ../../../input/your.xml to get to the xml
You are terribly wrong. It doesn't matter where your source file or class file located. Only thing is from where you are running your program from that location, you can calculate the relative path for the particular xml file.
Basically if you are running from eclipse the project root directory should be your project root, not under src/classes. You write below to see your current directory, and based on that you can create/modify your relative path to your xml.
Path path = Paths.get("");
System.out.println("REL PATH" + path.toAbsolutePath().toString());

Proper path for using ClassLoader.getResource()?

I've made a function(Java) that is supposed to read bytes from a file and print them to the console:
public void loadPixels(int size){
ClassLoader cl = this.getClass().getClassLoader();
pixels = new byte[size];
try{
InputStream stream = cl.getResource("res/" + fileName).openStream();
stream.read(pixels);
System.out.println(pixels.toString());
stream.close();
}catch(Exception e){
e.printStackTrace();
}
}
The problem is, I'm getting a NullPointerException on the line
InputStream stream = cl.getResource("res/" + fileName).openStream();
For the file I'm trying to open, the name is "font.spt", which is also the value held by fileName. This file is within the folder "res" in the project's root directory, and I'm currently using the Eclipse IDE.
Is my approach to the path for the file wrong, or is something else the issue?
To recap: fileName points to "font.spt", which is under the "res" folder in the bin directory.
EDIT: the "res" folder containing the .spt file is now under the "bin" for the project, rather than the root directory, but I still get the error. When running from the IDE or as an exported .jar, I still get the NullPointerException, where am I supposed to put these files? Can someone give me a screenshot or example?
By default, Eclipse will copy all non .java files it finds in the project's Source Locations to the Output Folder when it builds. So one option is to just place your resource files under the source folder along with your source code. However, a better option is to use a separate resources folder for non-Java files and declare that as an additional Source Location (via your project's Java Build Path properties). That's how Maven and Gradle projects are organized, too.
For example, you might have:
MyProject\
src\
java\
com\
....*.java
resources\
fonts\
font.spt
With both src\java\ and src\resources\ defined as Source Locations in the Build Path. Then your code to load the file would be like:
getResource("fonts/" + fileName)
Something to consider: use Gradle or Maven to manage your builds, both of which enforce/provide a project structure similar to this anyway.

Path to file in src directory

I am using a method that requires a string path to a file that is in my src directory structure in eclipse. Is the path to this file simply src\fileName.txt or is there a different way i should be getting this file as it doesnt seem to be working currently
Thanks
Run this and you will never forget how to remember.
File file = new File("sample.txt");
System.out.println(file.getAbsolutePath());
If you are following the maven standard directory structure, class files will be located relative to the classpath like so:
If you want SomeClass.class, you would access it by com.mydomain.packageorappname.deeperpackage.SomeClass. Is that what you are asking?

open resource with relative path in Java

In my Java app I need to get some files and directories.
This is the program structure:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass loads the resourcesloader class which will load my resources (directory and file).
As to the file, I tried
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
I have no idea which path to use for the directory.
I had problems with using the getClass().getResource("filename.txt") method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
src/main/resources
furthermore you can add subfolders in the resources folder
src/main/resources/textfiles
and say that your file is called myfile.txt so you have
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:
"/main/resources/textfiles/myfile.txt" path
or
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("") method is:
"/textfiles/myfile.txt"
here it is:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under `"myapp/target/classes"
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
Project/
src/ // application source code
org/
myproject/
MyClass.java
test/ // unit tests
res/ // resources
images/ // PNG images for icons
my-image.png
xml/ // XSD files for validating XML files with JAXB
my-schema.xsd
conf/ // default .conf file for Log4j
log4j.conf
lib/ // libraries added to build-path via project settings
I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:
static final ClassLoader loader = MyClass.class.getClassLoader();
// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");
NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
If you use an absolute path, both 'getResource' methods will start at the root folder.
#GianCarlo:
You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :
ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());
is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.
resourcesloader.class.getClass()
Can be broken down to:
Class<resourcesloader> clazz = resourceloader.class;
Class<Class> classClass = clazz.getClass();
Which means you're trying to load the resource using a bootstrap class.
Instead you probably want something like:
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
If only javac warned about calling static methods on non-static contexts...
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
Going with the two answers as mentioned above. The first one
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
Should be one and same thing?
In Order to obtain real path to the file you can try this:
URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;
Resourceloader is classname here.
"resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileUrl.openStream()));
I made a small modification on #jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
Use this:
resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**
One of the stable way to work across all OS would be toget System.getProperty("user.dir")
String filePath = System.getProperty("user.dir") + "/path/to/file.extension";
Path path = Paths.get(filePath);
if (Files.exists(path)) {
return true;
}

Categories

Resources