How to not hard-code a file path - java

I'd like to calculate the path of a file placed into Source Packages using this implementation:
URL pathSource = this.getClass().getResource("saveItem.xml");
When I try to create a new File like the code below:
File xmlFile = new File(pathSource.toString());
And I try to use it to create a document like this:
Document document = builder.parse(xmlFile);
This give me the java.io.FileNotFoundException.
How can I calculate the file path without hard-coding?
PS: I already used pathSource.getPath() but it doesn't work either.
I would like to use a similar implementation:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
PPS: The structure is the following:

You can't access a resource that inside a JAR file as a File instance. You can only get an InputStream to it.
As such, the following line
File xmlFile = new File(pathSource.toString());
won't work properly and when an attempt is made to read it later, a FileNotFoundException will be thrown.
Assuming you're trying to parse a XML file using DocumentBuilder, you can use the parse(InputStream) method:
try (InputStream stream = this.getClass().getResourceAsStream("saveItem.xml")) {
Document document = builder.parse(stream);
}

Short answer - saveItem.xml is not in the classpath.
If it is a web application, then file may be added to WEB-INF/classes folder.
Edit:
Try this.getClass().getResourceAsStream() too.

getClass().getResource("saveItem.xml");
looks for the file in the same package (which are directories when you look at the file system) as the class that getClass() returns.
Make sure the file is in there. Also make sure it's really in there when you run your code, there's a difference between your source folder and the target or bin folder where the compiled class files are placed.
Also check what pathSource.toString() contains.

Related

Jar null point exception when reading a file

The following code works fine on my Eclipse IDE.
private void getLayersAndDisplay() throws Exception {
URL imageURL = ImageLab.class.getResource("earthlights.jpg");
File imageFile = new File(imageURL.toURI());
URL shapeFileURL = ImageLab.class.getResource("countries.shp");
File shapeFile = new File(shapeFileURL.toURI());
URL shapeFileURL2 = ImageLab.class.getResource("Brasil.shp");
File shapeFile2 = new File(shapeFileURL2.toURI());
displayLayers(imageFile, shapeFile,shapeFile2);
}
However, when compiling to a jar, it gives me a null pointer exception. I thought that since I am getting it as a class.getResource, it would work. Can't I use the File class in a jar? Not even in a cast?
Thank you
An entry of a zip file (that's what a jar file is) is not a file existing in your file system. So you can't use a File, which represents a path on your filesystem, to refer to a zip entry. And you can't use file IO to read its content, since it's not a file.
I have no idea what you want to do, but if you want to read the content of the jar resource, just use ImageLab.class.getResourceAsStream() to get an InputStream back, reading from the entry.

How to read properties file inside jar?

I have a config.properties file under the package com.abc.properties. From one of the java class present in com.abc.util, I need to read the property file. Both the files are present inside jar.
I have tried using
fs = new FileInputstream(VerifyFolderStructure.class.getResourceAsStream("com/abc/properties/config.properties"));
But it doesn't seem to work. Please help.
P.S: VerifyFolderStructure is my java class from which I need to load the properties file.
To obtain the stream you don't need FileInputStream at all. You can get the properties' file stream like this
InputStream is = VerifyFolderStructure.class.getResourceAsStream("/com/abc/properties/config.properties");
I think you need to add "/" in the front of you path.if you don't add "/" that means the properties is located in the same packages path as VerifyFolderStructure class.

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Create a java file inside a package

Currently, my plugin creates a java file in my project(IProject). But I want that java file within a specified Package. How to do it.
IFile sampleFile = parentFolder.getFile("Sample.java");
if(!sampleFile.exists()) FileInputStream fileStream = new FileInputStream("C:\Users\Uma\Desktop\treasureHunt\Application.java"); sampleFile.create(fileStream, false, null);
This is my current piece of code.
How can I create the sampleFile within a package. For example: in package com.mdh.se as com.mdh.se.Sample.java
If you have a "package" (e.g. "com.mdh.se") then you'll have a corresponding subdirectory (for example, "c:\users\uma\desktop\treasurehunt\com\mdh\se"). Simply write your file there.
I think, that the only thing you need to do is to create folders representing your package structure. So your path should look like C:\Users\Uma\Desktop\treasureHunt\com\mdh\se\Sample.java for your example.
You can get a special file inside the package by calling
java.net.URL imgURL = ResourceManager.class.getResource( "ResourceManager.class" );
From these URL you can extract the directory, the file is placed.
A new file you can create with
new File(directory,filename);

How can I get relative path of the folders in my android project?

How can I get the relative path of the folders in my project using code?
I've created a new folder in my project and I want its relative path so no matter where the app is, the path will be correct.
I'm trying to do it in my class which extends android.app.Activity.
Perhaps something similar to "get file path from asset".
Make use of the classpath.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/to/folder");
File file = new File(url.toURI());
// ...
Are you looking for the root folder of the application? Then I would use
String path = getClass().getClassLoader().getResource(".").getPath();
to actually "find out where I am".
File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));
With this I found my project path:
new File("").getAbsolutePath();
this return "c:\Projects\SampleProject"
You can check this sample code to understand how you can access the relative path using the java sample code
import java.io.File;
public class MainClass {
public static void main(String[] args) {
File relative = new File("html/javafaq/index.html");
System.out.println("relative: ");
System.out.println(relative.getName());
System.out.println(relative.getPath());
}
}
Here getPath will display the relative path of the file.
In Android, application-level meta data is accessed through the Context reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images.
I found in search that in JAVA, we can get path from Root to folder which we specify as,
String myStorageFolder= "/images"; // this is folder name in where I want to store files.
String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);
Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,
C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images
With System.getProperty("user.dir") you get the "Base of non-absolute paths" look at
Java Library Description

Categories

Resources