I have an executable JAR that has a file in it that i want to open as a java.io.File instance from code (not InputStream or anything else...just File).
Its a maven project and the file is at the root of "src/main/resources/file.xxx"
The file is located at the root directory of the jar after packaging(verified that its there).
My first attempt: FileNotFoundException
java.io.File myFile = new java.io.File("file.xxx");
someMethodThatUsesTheFile(myFile); //I really need it to be a file!!!
Other attempts: FileNotFoundException
java.io.File myFile = new java.io.File("/file.xxx");
java.io.File myFile = new java.io.File("classpath:file.xxx");
java.io.File myFile = new java.io.File("classpath:/file.xxx");
I am not sure whats really going on. Web Apps can easily just load everything from the webapp root directory, Im confused as to why JAR apps behave differently.
Additional Info:
Using Java8 as runtime/build
command to run the JAR: "java -jar myjar.jar"
Application Code and file are both located in the same jar
Short Answer: It is not a "File", so you just cant do it.
The JAR file is a File, but not its contents.
Alternatives would be:
Try other overloaded versions of that method, InputStreams are
usually your options, you can load it using this code:
InputStream is = getClass().getResourceAsStream("file.xxx");
Move that file out of the JAR and into the same directory of the JAR (consider the security risks)
Try this one may help you :
URL url = this.getClass().getResource("src/main/resources/file.xxx");
File file= new File(url.toURI());
Related
I have an awt application which will be run using executable JAR file. Few Issues I am facing in getting resources folder
1. In Eclipse, If I use following code
properties = new Properties();
InputStream in =getClass().getResourceAsStream("resources/template.properties");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Then I am getting
ERROR 2019-11-11 12:03:44,052 [AWT-EventQueue-0]
java.lang.NullPointerException
If I use the above code in eclipse and when I export runnable Jar then it is working in JAR file but when I run in eclipse it is throwing nullpointer exception.
Case 2: But if I use below code and export JAR file then JAR file is throwing error as "in current directory resources is not available" even resources folder is present.
properties = new Properties();
InputStream in =
inputStream = new FileInputStream("resources/template.properties");
Folder structure
enter image description here
You shouldn't reference the resource folder in the file path string. But then, your resource folder needs to be a source folder for Eclipse.
I don't know your project strcuture yet, but I suggest you to create a resource folder on your project root, then rigth click on it and go to Build Path > Use As a Source Folder.
After that, all files inside that folder will both be directly accessed by the getResourceAsStream method, and also be placed on the JAR root, merged with all other files from the other source folders.
Then you can do:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template.properties");
This way should work both inside Eclipse and in the standalone JAR.
PS: I strongly suggest you to start using Maven projects and follow its folder structure.
You don't need to specify the resources path if you do like this snippet bellow it might work.
InputStream inputStream = getClass()
.getClassLoader().getResourceAsStream("template.properties");
I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).
I have a Java console applicaton with a resources folder. It works OK, but when I want to export my code to a runnable Jar file(with Eclipse), then the exported Jar can not find the files(they are in buildpath) and give a Filenotfound exception.
When I unzip the exported Jar file I can see the files are there in the root folder, so I guess something wrong with my code.
BufferedReader srcFile = new BufferedReader(new FileReader("resources/"+filename));
String line = srcFile.readLine();
I tried to use
URL url= ClassLoader.getSystemResource(filename);
filename=url.tostring();
But no luck.
Use getResourceAsStream(String) (docs) if you want to read in a resource on the classpath.
Been looking for this for the past 2 hours and can't find anything (I've found solutions to the same problem but with images, not text files).
Pretty much, I made a program that reads a text file. The file is a list of names and IDs. Using Eclipse, I put the file in my src folder and in the program put the path file to it. Like this:
in = new BufferedReader(new FileReader(curDir+"\\bin\\items.txt"));
Where curDir is the user's current directory (found with System.getProperty("user.dir")).
Now, problem is, the program runs fine when I run it from Eclipse, but when I try to make it a runnable JAR and then run it, the program runs, but the info from the text file does not load. It look like Eclipse is not putting the text file with the JAR.
EDIT: Solved-ish the problem? So the JAR file needs to the in a folder with all the original files? I am so confused, what is a JAR file then?
A more robust way to get a file whether you are running from Eclipse or a JAR is to do
MyClass.getResource("items.txt")
where MyClass is a class in the same package (folder) as the resource you need.
If Eclipse is not putting the file in your JAR you can go to
Run -> Run Configurations -> -> Classpath tab -> Advanced -> Add Folders
Then add the folder containing your file to the classpath. Alternatively, export the Ant script and create a custom build script.
To the point, the FileReader can only read disk file system resources. But a JAR contains classpath resources only. You need to read it as a classpath resource. You need the ClassLoader for this.
Assuming that Foo is your class in the JAR which needs to read the resource and items.txt is put in the classpath root of the JAR, then you should read it as follows (note: leading slash needed!):
InputStream input = Foo.class.getResourceAsStream("/items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
Or if you want to be independent from the class or runtime context, then use the context class loader which operates relative to the classpath root (note: no leading slash needed!):
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
(UTF-8 is of course the charset the file is encoded with, else you may see Mojibake)
Get the location of your jar file
Firstly create a folder(say myfolder) and put your files inside it
Consider the following function
public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0]+"myfolder/";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Suppose your jar file is in D:\Test\dist
Then path() will return /D:/Test/dist/myfolder/filename
Now you can place 'myfolder' inside the folder where your jar file is residing
OR
If you want to access some read-only file inside your jar you should copy it to one
of your packages and can access it as
yourClassname.getResource("/packagename/filename.txt");
I'm trying to get the path to a file that it is located out of the java jar and I don't want to use an absolute path. An exampel: lets say that the jar is located in ~/lib/myjar.jar and the file is located in the same folder. What I've trying is something like this, but it fails:
File myfile = new File(this.getClass().getResource("../../../").toURI());
Note: my package is com.contro.gui, that's why I have "../../../", in order to acces to the "root"
I'm not sure how I can access to the file. Any suggestion?? And what about if the file that I want to access is in other folder like ~/res/ ???
If the file is in the same directory as the jar, I think this will work (feels fairly hacky, but...):
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = new File(url.toURI());
File dir = myfile.getParentFile(); // strip off .jar file
(Haven't tested this, but it seems feasible. Will only work with file-based jars of course).
If the file is in some random location, I think you will need to either pass in parameters or check "known" locations like user.home. (Or, you could always put the file in the jar a use getResource().)
No just do
File FileName = new File(".");
String Directory = FileName.getCanonicalPath();
that will get you the parent directory of your class in a file or jar just remember to set the directory if it's in a jar like this "NameOfJar\NameOfFolder\etc"