Launching a text file from a .jar file (File path?) - java

I'm trying to launch a text file from a .jar file using Desktop.getDesktop().open(file)
String fileName = "file.txt";
URL url = getClass().getResource(fileName);
File fileToRead = new File(url.toURI());
Desktop.getDesktop().open(fileToRead);
I omitted the try-catch blocks for simplicity.
It is able to open my file when run from eclipse. But once I export to a .jar file, I get a NullPointerException in File fileToRead = new File(url.toURI());

When you package a class in a .jar file, it usually makes it nested one level deeper.
Therefore, you can try changing the first line to:
String filename = "../file.txt";

Looking at the JavaDoc of Class.getResource(String):
an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
Parameters:
name - name of the desired resource
Returns:
A URL object or null if no resource with this name is found
Your resource was not found, hence NullPointerException. Specify the path within the JAR as described by the JavaDoc (absolute path starting with '/' or relative to the class of this, the object where you are calling getClass().getResource(fileName)) and you should get it.

Related

getClass() getResource returning null

When I try and load a image from a resource directory in eclipse I keep getting a null pointer exception (NPE).
The res folder is in the project directory.
This where I get the NPE:
image.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("res/bg.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
When I remove the getClass().getReource() the image is returned:
image.setIcon(new ImageIcon(new ImageIcon(("res/bg1.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
When I print the URL for the res directory I get null:
URL resource = this.getClass().getResource("/");
resource.getFile(); // print me somehwere
URL resource1 = this.getClass().getResource("/res");
resource.getFile(); // print me as well
URL resource2 = this.getClass().getResource("res/bg2");
resource.getFile(); // print me as well
System.out.println("Reource1 : " + resource);
System.out.println("Reource1 : " + resource1);
System.out.println("Reource1 : " + resource2);
Output:
Reource1 :file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
Reource1 : null
Reource1 : null
I have refreshed, cleaned, and built the project several times.
Directory:
Any idea why this is happening?
Thanks
Replace this.getClass().getResource("res/bg.jpg") with this.getClass().getResource("../res/bg.jpg")
Since this.getClass().getResource("/") returns file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/, you need to go one level(directory) up in the directory structure so that you can enter the res directory. It's like cd ../res from the current location of file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
Note: I can't see bg.jpg in the screenshot that you have attached. Make sure, you have bg.jpg in this path.
From the official java doc: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String).
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
I think, you got the directory structure wrong.
If '/' points to the bin directory, as shown by the output of your first resource, '/res' points to the res subdirectory of bin and not to the sibling in the parent directory of bin.
You need to either move the res directory or change the way the resolution of '/' works.
The rules for searching resources associated with a given class are
implemented by the defining class loader of the class.
from Java documentation
For maven based projects the resource directory is usually src/main/resources.

Selenium - Java: How to get absolute path to the file

I created the method where I get an absolute path but when I debug I get an incorrect path to the file which should be uploaded.
So, the method where I get absolute path:
public String getFilePathByFormat(String filePath) {
File file = new File(filePath);
return file.getAbsolutePath();
}
Then I use this method in the general low-level method for uploading:
public void uploadFile(WebElement webElement, String filePath){
try {
webDriver.manage().timeouts().implicitlyWait(40, SECONDS);
webElement.sendKeys(getFilePathByFormat(filePath));
}catch (Exception e){
printErrorAndStopTest();
}
}
And when I debug and evaluate incorrect path gets:
E:\acceptance-tests\src\test\resources, BUT after disk name, one more folder should be - where the project located.
What's wrong and why getAbsolutePath doesn't build the correct path?
Thanks
There are two types of file path in file system.
1) An absolute path always starts from root element and contains complete directory list required to locate the file. For example, '/Users/username/filename.txt' on Unix systems or 'C:\Users\username\filename.txt' on Windows systems.
A relative path does not have any directory listing and needs to be combined with another path in order to access a file. For example, username/filename.txt is a relative path; Note that it does not have any forward or backward slashes at the beginning.
getAbsolutePath() returns the absolute path of a file and works like below.
File object is created with absolute pathname - This method simply returns the pathname provided to create the file. And in case of Windows System, drive name is appended at beginning by default if it is not present in absolute path name given.
File object is created using relative path - Here relative path name is made absolute by resolving it against the current user directory.
In this case, absolute path '/acceptance-tests/src/test/resources/test4.pdf' is passed; As mentioned for windows system, drive details are prefixed with given path and returned as absolute path.
To make it work, you can pass the relative path of file 'src/test/resources/test4.pdf' or just pass the file name 'test4.pdf'.

NullPointerException on an existing path

I get a problem while creating a Classifier. My existing path to it causes a NullPointerException. I am working with OpenCV 2.4.11 in Eclipse. The OS is Windows that's why I added another backslash between folders. When I insert the path with single backslashes in a file explorer it opens the XML File correctly. My code looks like this:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
String path = "C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
System.out.println("path:" + path);
CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource(path).getPath());
The output is:
Running FaceDetector
path:C:\Users\Juergen\OpenCV\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml
Exception in thread "main" java.lang.NullPointerException
at FaceDetector.main(FaceDetector.java:24)
The code is based on the following instruction.
Any ideas on why the NullPointerException is thrown are appreciated.
Thanks
When we look at the Java API wi find this:
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Therefore you must add a '/' in front of your absolute path:
String path = "/C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
And you also should get rid of the windows file separator. Java understands the unix file separator and knows how to handle that on a windows system:
String path = "/C:/Users/Juergen/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";
I replaced my string by Yours, nothing changed. Still get a NullPointerException. The check
if (!new File(path).exists()) { throw new FileNotFoundException("Yikes!");}
does not throw any Exception – Jürgen K
Then from the *.class.getResource(path) you get an URL and from the URL's getPath() method you get a String which should most likely be the same as your original string.
Did you try to use it directly (with the leading '/')?

How does file.getAbsolutePath work?

This is the code:
String filename = "sql.txt";
File file = new File(filename);
String path = file.getAbsolutePath();
System.out.println(path);
My text file resides in E drive but when I print out the path it is in C drive. Why does this happen?
You have provided a path which is neither absolute nor canonical.
String filename = "sql.txt";
Hence, the pathname is returned as simply the current user directory.
Have a look at the documentation for the getAbsolutePath() method in the File class:
If this abstract pathname is already absolute, then the pathname
string is simply returned as if by the getPath() method. If this
abstract pathname is the empty abstract pathname then the pathname
string of the current user directory, which is named by the system
property user.dir, is returned. Otherwise this pathname is resolved in
a system-dependent way. On UNIX systems, a relative pathname is made
absolute by resolving it against the current user directory. On
Microsoft Windows systems, a relative pathname is made absolute by
resolving it against the current directory of the drive named by the
pathname, if any; if not, it is resolved against the current user
directory.
Follow those steps
Go to run configuration
Click argument tab
Change the working directory to ${workspace_loc:myproject}
Reference
Java workspace and file path

getResources() returns null

Using Eclipse IDE. The line:
getClass().getResource("/res/bitmaps/image.png");
returns null. I have created the res folder in the root of my project.
The code of interest is:
bImage = ImageIO.read(getClass().getResource("/res/bitmaps/image.png"));
and it throws the exception:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1378)
at com.example.game.resource.Resources._loadImage(Resources.java:31)
at com.example.game.GameComponent.<init>(GameComponent.java:19)
at com.example.game.GameFrame.<init>(GameFrame.java:8)
at com.example.game.GameFrame.main(GameFrame.java:13)
Any help?
ImageIO.read(getClass().getResourceAsStream("res/drawable/image.png"));
Make sure res folder is in class path, verify using project properties > Java build Path > Source tab. If not in class path, can add via Add Folder.. button on the right.
You say the resource is in "the root of my project" - is it that folder in your build path? You need to have it in your build path so that Eclipse will copy it to the output directory (bin by default).
getClass().getResource("/res/drawable/image.png");
You should give the path of the folder in which image.png exists
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
package_name/name
Where the package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Categories

Resources