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.
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");
getClass().getResource works fine in Eclipse and returns the path for a file I want to have access to, but after exporting the JAR file my files don't load anymore.
I already tried to print out my path; in Eclipse the console shows:
/C:/Users/.../eclipse-workspace/GameJumpAndRun/bin/file/save1
...but if i run the JAR file by using cmd the message is
file/save1, and no files have been loaded.
System.out.println(getClass().getResource("/file/save"+i).getFile());
file = new File(getClass().getResource("/file/save"+i).getFile());
I need the file as a File and not as a BufferedReader; is there a way to get the same file in both Eclipse and the exported JAR?
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());
So in Eclipse this code works:
String file_path = "accounts.accs";
File file = new File("src/puffinlump/folder_lock/"+file_path);
But when I compile it into a JAR I get this error:
Error reading file: java.io.FileNotFoundException: lock\src\puffinlump\folder_lock\accounts.accs (The system cannot find the path specified)
Why is it not working and how can I fix it?
As Obicere said, the working directory is the project directory. You try to access something in the src folder, which probably doesn't exist wherever you exported your JAR. You should create a folder named folder_lock in your project directory with accounts.accs in it, then get your file with:
File file = new File("folder_lock" + File.separator + "accounts.accs");
If you need it in your JAR (which it's being exported to, given that it's in the src folder) then retrieve an InputStream from it like this:
InputStream stream = getClass().getClassLoader().getResourceAsStream("puffinlump/folder_lock/accounts.accs");
If your method is static, use
InputStream stream = MyClass.class.getClassLoader().getResourceAsStream("puffinlump/folder_lock/accounts.accs");
instead, substituting your class name over MyClass.
If you need an URL, you can retrieve one with getResource instead of getResourceAsStream.
Note that your code must be compiled to run - Eclipse compiles it by default every time you save.
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");