How to get a String value of resources folder (Java) - java

I'm a beginner in programming and I have a class that requires a path to some folder in its constructor. For example:
SomeClass class = new SomeClass(c:/folder);
I need to get a String value of resources folder (only path to folder without specific file names). A method in that class will add a filename to path from constructor and do some operations with a specific file.
I'm trying to do this (bad code!), but just have npe:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("src/main/resources").getFile());
String path = file.getAbsolutePath();
So, the question is: how to get String value of resources folder?

What solved my problem:
File file = new File("src/main/resources");
String path = file.getAbsolutePath();
So, I got String path to resources folder.

Related

Reading a jar file from resource location

In my application I have to read a jar file available in the disk location and segregate .classes file from the jar.
Code is
JarFile jarFile = new JarFile("./resources/CD.jar");
for(Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements();) {
String s= em.nextElement().toString();
ZipEntry entry = jarFile.getEntry(s);
String fileName = s.substring(s.lastIndexOf("/")+1, s.length());
if(fileName.endsWith(".class")){
System.out.println(fileName);
}
But I am getting an error
java.io.FileNotFoundException: .\resources\CD.jar (The system cannot find the path specified).
I found a solution to my problem:
Add the 'resource' location to the classpath
Allow external service API to place cd.jar in resources location
Using a child class loader add the cd.jar to the classpath
code snippet is given below:
URLClassLoader childLoader = new URLClassLoader(new URL[] { getURLOfTestclass() }, this.getClass().getClassLoader());
URL url = getClass().getClassLoader().getResource("CD.jar");
return url;
Did you try adding the CD.jar file in your classpath? I would try doing that once.
Change ".\resources\CD.jar" to a fully qualified URI. Eg:C:\Users\Whoever\Documents\resources\CD.jar.

Absolute Path from File in Package

Let's say I have a package: com.example.resources and inside it I have picture.jpg and text.txt - How can I use only the package path to identify the absolute filepath of picture.jpg and text.txt?
Is this correct?
File file1 = new File("/com/example/resources/picture.jpg");
file1.getAbsolutePath();
File file2 = new File("/com/example/resources/text.txt");
file2.getAbsolutePath();
"I'm trying to reference those files within the application so that when I deploy the application to different systems I won't have to reconfigure the location of each resource "
You don't want to use a File, which will load from the file system of the local machine, you want to load through the class path, as that's how embedded resources should be read. Use getClass().getResourceAsStream(..) for the text file and getClass().getReource(..) for the image
Your current path you're referencing looks like it should work, given the package name you've provided.
Take a look at this answer and this answer as some references.
I've figured out how to do it. Here is the code that I used:
public String packagePathToAbsolutePath(String packageName, String filename) {
String absolutePath = "File not found";
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
File[] files = new File(root.getFile()).listFiles();
for (File file : files) {
if (file.getName().equals(filename)) {
absolutePath = file.getName();
return absolutePath;
}
}
return absolutePath;
}
This method was really useful because it allowed me to configure the resource paths within the application so that when I ran the application on different systems I didn't have to reconfigure any paths.

How to get and use the path of a folder in eclipse project?

I create a new folder Fold inside my eclipse project Proj. How do I get the path of Fold relative to Proj ? This folder will be used as place to store serialized objects. Will I be able to serialize and de-serialize my code using this relative path ?
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/folder");
or
URL url = getClass().getResource("path/folder");
This code gets the path -
String absolutePath = new File(".").getAbsolutePath();
System.out.println(absolutePath);// Shows you the path of your Project Folder
int last = absolutePath.length()-1;
absolutePath = absolutePath.substring(0, last);//Remove the dot at the end of path
System.out.println(absolutePath);
String filePath = "MyFolderInsideEclipseProject\\file.txt";//You know this
System.out.println(absolutePath + filePath);//Get the full path.

Accessing resource file from class path

I am trying to access my resource files from my class path. I have stored all my resources in a folder called "config" which has been added to my build path.
Now the problem is, i am unable to access them. I have tried following options, but none of them seems to work. Everything returns null.
String resourceName = "/config/LPANewCommonModelSchema.xsd";
System.out.println(getClass().getClassLoader().getResource(resourceName));
System.out.println(getClass().getResource(resourceName));
System.out.println(Thread.currentThread().getContextClassLoader().getResource(resourceName));
String resourceName = "config/LPANewCommonModelSchema.xsd";
System.out.println(getClass().getClassLoader().getResource(resourceName));
System.out.println(getClass().getResource(resourceName));
System.out.println(Thread.currentThread().getContextClassLoader().getResource(resourceName));
String resourceName = "/LPANewCommonModelSchema.xsd";
System.out.println(getClass().getClassLoader().getResource(resourceName));
System.out.println(getClass().getResource(resourceName));
System.out.println(Thread.currentThread().getContextClassLoader().getResource(resourceName));
String resourceName = "LPANewCommonModelSchema.xsd";
System.out.println(getClass().getClassLoader().getResource(resourceName));
System.out.println(getClass().getResource(resourceName));
System.out.println(Thread.currentThread().getContextClassLoader().getResource(resourceName));
EDIT:
Somebody asked for hierarchy,
Thanks in advance,
Harsha
Try with this (assume the current calss is beside resources folder)
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("config/LPANewCommonModelSchema.xsd");
or this
InputStream in = this.getClass().getResourceAsStream("/config/LPANewCommonModelSchema.xsd");

Getting the directory name in java

How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder

Categories

Resources