Java: Pathnames not working once I export to JAR [duplicate] - java

This question already has answers here:
How to read file from relative path in Java project? java.io.File cannot find the path specified
(15 answers)
Closed 6 years ago.
I have exported a project to a runnable JAR in eclipse. There are a few places in my code where I've done the following.
String file = "src/Files/...";
loadFile(file); // purely for example
Now that the project is in the form of a JAR, those directories don't seem to exist and loading those files fails. I'm pretty sure that the files I'm referencing are packed in the JAR. Do the directories change in any particular way when exported to JAR? Any other ideas on how to make this work?

You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.
Assuming that you've a foo.txt file in package com.example, then you can get an InputStream of it as follows
InputStream input = getClass().getResourceAsStream("/com/example/foo.txt");
// ...
Or when you're inside static context
InputStream input = SomeClass.class.getResourceAsStream("/com/example/foo.txt");
// ...
Or when you want to scan the global classpath
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/com/example/foo.txt");
// ...
See also:
How to read file from relative path in Java project? java.io.File cannot find the path specified
getResourceAsStream() vs FileInputStream

Related

IntelliJ txt file doesn't get included when building jar file [duplicate]

This question already has answers here:
FileNotFoundException in src/main/resources
(4 answers)
Closed 2 years ago.
I am trying to build my project to a jar file. When I first opened the jar file I noticed nothing happened. I then launched the jar file from cmd. Then I saw it throws an error because it cannot find a txt file. This is the error:
Executing the program in IntelliJ works fine so I am assuming the txt file is not included in the artifact. This is how I use the txt file in the code:
This is what my file structure looks like:
This is what my artifact settings look like:
I tried putting the txt file in the src folder and manually including it in the artifact settings, I tried putting the txt file in the resources folder (It is marked as Resources Root) and I tried using the resources folder and also manually adding the resources folder to the artifact settings (this is the last thing I tried and is visible in the picture of my artifact settings).
I am really confused why the txt file doesn't seem to be in the jar file. Any help would be really appreciated.
Place the file in the resources folder, and instead of File try using getResourceAsStream to get the contents of the file:
InputStream in = getClass().getResourceAsStream("/data.txt");
Scanner pathScanner = new Scanner(in);
Make sure to set ?*.txt as resource pattern in the compiler options.

Why embedded File not found exception in executable jar file? [duplicate]

This question already has answers here:
Load a resource contained in a jar
(3 answers)
Closed 6 years ago.
There is binary file for update my switch configuration in src/main/resources directory in run time. when i try it with debug mode in eclipse the file exist and there is no problem, but when i create an executable jar file for real application this file does not exist.
Where is the problem?
String filePath = new File("/resources/firmwares/myConfigFile.bin").getAbsolutePath();
File f = new File(filePath);
if (f.exists())
upload();
Assuming that you are using Maven and you added the resource plugin so during maven build it will copy your resources to the target dir and then during packaging it will also package them
Once your JAR is created you will need to use another method to access your file since now your file is packaged within the JAR file
To access a file that is located inside a JAR file use:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("firmwares/myConfigFile.bin");
Or
URL url = this.getClass().getClassLoader().findResource("firmwares/myConfigFile.bin");

Using getResourceAsStream is not working in Java [duplicate]

This question already has answers here:
How to read text file from classpath in Java?
(17 answers)
Closed 7 years ago.
I have a very simple method which uses the getclass().getResourceAsStream() method to read a file. However it always returns null and I can't figure out what is wrong. Here is my piece of code.
InputStream sw = getClass().getResourceAsStream("/filename.txt");
BufferedReader bf = new BufferedReader( new InputStreamReader(sw));
sw always remain null. the file filename.txt exist in the root directory of my project.
EDIT:
I found the reason. I realized that I was running my project from Eclipse and the project was not part of the classpath on my PC. However if I package my program as a jar file and then run it, the files in the jar file are considered as resources and can be read using the getResourceAsStream() method.
The method Class.getResourceAsStream() looks for the designated resource within the Java class path, not based on the project root.
The project root usually is not part of the classpath. Instead, you should have a src folder (or a similar name), which contains the Java files and may also contain your text file. Or, if you use Maven, you have folders src/main/java and src/main/resources, which are classpath roots. In this case, the text file should reside in the resources folder.
If your project gets packaged into a .jar file, all its resources are packaged in the .jar file along with the .class files, and will be found by Class.getResourceAsStream().
Root of your project is not always the root of the path from the ClassLoader point of view.
Easiest way to find out where it is trying to load the resource from:
System.out.println(MyClass.class.getResource("/").getPath());
And after that you may be able to easily find out the part of the project or run configuration that causes the difference between your assumption and the reality about the right placement of the file.
getResourceAsStream() reads a resource file, ie a file into .jar file (or resource directory), not a regular file in working directory on disk. Use FileReader to read a file from disk
user likewise,
InputStream sw = this.class.getClassLoader().getResourceAsStream("filename.txt");
Note : filename.txt file should be present on classpath.
Just to be complete, here's a simple test that does print out the absolute path of a resource. You can use this inside any class to find the location of that class on your hard drive, in case it isn't obvious what your build system is doing. Just substitute the name ErrorTest for the class you are checking.
public class ErrorTest
{
public static void main(String[] args )
{
final String className = ErrorTest.class.getSimpleName().replace( '.', '/').concat(".class");
System.out.println(ErrorTest.class.getResource(className).getPath() );
}
}
Output of this program:
run:
/C:/Users/Brenden/Google%20Drive/proj/tempj8/build/classes/quicktest/ErrorTest.class
BUILD SUCCESSFUL (total time: 0 seconds)

Using a manifest file as input in a webapplication [duplicate]

This question already has answers here:
How do I read the manifest file for a webapp running in apache tomcat?
(7 answers)
Closed 8 years ago.
I want to use my manifest.mf file as an InputStream so I can retrieve some of the data that is inside. I use the following line of code:
inputStream = new FileInputStream("../../../../WebContent/META-INF/MANIFEST.MF");
Because the java class and the manifestfile are located in the following directory:
Unfortunately, this path always give me a FilenotFoundException. What is the correct path to refererence this file?
You want to load a file that is bundled with your web application application. This file will be part of the war file of your deployed app. It thus won't be on the file system. So loading it with a FileInputStream is not the right solution.
BTW, file paths are not relative to the class creating the FileInputStream. They're relative to the directory from which the application server is launched.
The way to load webapp resources is to use the ServletContext.getResourceAsStream() method. Read its javadoc (and the javadoc of ServletContext.getResource()) carefully.
You should also realize that WebContent is the name of the directory where the sources of your webapp are. Once packaged and deployed on a server, there won't be any WebContent directory anymore.
try this:
File file = new File("../../../../WebContent/META-INF/MANIFEST.MF");
System.out.println(file.getCanonicalPath());
see where your app think the file is located and fix the path

Reference directories correctly when launching a .jar from a batch file [duplicate]

This question already has answers here:
How to get the path of a running JAR file?
(33 answers)
Closed 9 years ago.
How to reference directories correctly when launching a .jar from a batch file?
I am trying to launch a jar file from a .bat . One of the first things my code does is open and read from a file. I reference the file like this:
final ArrayList<EmailAccount> emailList = FileIO.getListOfAccountsFromFile(".\\EmailList\\list.txt");
Everything works fine if the batch file is in the same directory as my jar. HOWEVER, if I put my batch file somewhere else and try to run it (like i plan to have it work), the program thinks that I'm trying to reference a file that is in the
".bat directory"\EmailList\list.txt
instead of
".jar directory"\EmailList\list.txt
and comes up with a fileNotFoundException.
Is there any way that I can run my batch file from a different directory while correctly referencing files in relation to the jar without hard coding in the jar's file path?
You can ask the JVM about the location of a given class. If you know it is inside the jar you refer to, then you can then extract the location of the jar file, and then construct your file objects relative to that.
See https://stackoverflow.com/a/320595/53897 for details about
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

Categories