I have a java project which should read file in a external folder. I give the file path as '../FolderName' in the class. But if I generated a jar file from this project, it cannot read the file. What is the correct way to define the folder path in this kind of situations ?
You should use java.lang.Class.getResourceAsStream(String).
It reads the file from inside your JAR.
Example:
InputStream in = getClass().getResourceAsStream("/classpath/to/my/file");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
A good Reference : How to read a file from a jar file?
The correct way to pass the absolute path to your code (jar) as program argument.
java -jar myjar.jar abs_path
You can then access the absolute path in the main() method of your class (mentioned in the manifest.mf file of a JAR) as follows:
String filePath = args[0];
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/classpath/toyourfile");
Related
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());
I have a .jar file and at root of them located a folder. How I can read this folder into java File class?
You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream() to get the contents of the folder, like this:
InputStream in = getClass().getResourceAsStream("/FILENAME.TXT");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
For my Java application, I use some input files inside src folder. But after I create the jar file and use it, it gives an error saying cannot find the file.
How to add an input file when creating jar file in NetBeans?
You need to use getResourceAsStream(String name), to get a stream to the file:
InputStream is = MyClass.class.getResourceAsStream("fileName");
This will return an input stream to the file fileName which is located inside a directory that MyClass.class is in.
I have two jar files "jar1.jar" and "jar2.jar" in my classpath
now there is a file test.xml in "jar1.jar" , which can be read from my program
by this
x=reader.readXml("test.xml");
but if i try to access some file from "jar2.jar" my program is not reading it,
is there a way to tell program that you need to read from this jar file, because its only reading from jar1 but not jar2..
thanks
make jar1 in your class path,
In any class in jar2, try this:
InputStream is=this.getClass().getResourceAsStream("/path to xml/test.xml");
BufferedReader br=new BufferedReader(new InputStreamReader(is));
You will have to adjust import order for your jar files. Go to project->properties->Java Build Path->Order and Export and make the jar2 up in the export order. I presume You have same file in both jar files.
If your file in jar2 has different name so, you have to verify:
This jar file is in your class path
Your pointing to a correct XML file location.
After above checks, you can use following line of code to read file.
InputStream stream = getClass().getResourceAsStream("<valid path to xml>");
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");