unable to read config.properties in java with jar file - java

I'm new to java , i have file named config.porperties
i put it in this path /home/user/workspace/myproject/config.properties
but when i submitted the jar file after packaged it i got that it cannot find this file
java.io.FileNotFoundException: config.properties (No such file or directory)
the code
FileInputStream finputstream = new FileInputStream(
"/home/user/workspace/myproject/config.properties");
prop.load(finputstream);
but there is no error in the code i think the problem with jar file that it couldn't read the path !
Hope i can find help , THANKS

I am not sure what happend during "but when i submitted the jar file after packaged it". Your code still tried to load home/user/workspace/myproject/config.properties. So check whether that file exists and is readable.
If you want the file to reside on a different path - you have to change your code as the path is hardcoded.
if you expect the config.properties to be packaged within the jar and loaded from there, change your code to something like
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file/config.properties");
Watch out: Again you are hardcoding a path but you can ensure the file will reside at that location within the jar.

Related

Load a file outside of a Jar

I have a folder called lib that contains all my Jar files and in one of the Jar files class, I have a main method which is called by a batch file. In the same folder location as my lib, I have another folder structure path/to/a/resource/myresource.txt
How can I load this file from a class inside the Jar file? I tried the following and both resulted in null:
getClass().getResource("path/to/a/resource/myresource.txt")
getClass().getClassLoader().getResource("path/to/a/resource/myresource.txt")
Any ideas? Even with an absolute path, it failed! Any suggestions?
You can use:
getClass().getResourceAsStream("path/to/a/resource/myresource.txt")
However, for this to work, you need to add the path '.' to the Class-Path entry of the JAR's MANIFEST.MF file.
http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
Two things you tried are used to read files from class-path since this folder is not on your classpath you can read it directly with any of the java File IO classes.
File file = new File("C:/folder/myFile.txt");
or if you know the relative path:
File file = new File("../../path/myFile.txt");
Your path seems not to be precise enough. Further, this question has been worked before.
Have a look here:
How to Load File Outside of, but Relative to, the JAR?
How to get the path of a running JAR file?
You can either load the file from file system
new FileReader(relativeOrAbsoluteFilesystemLocation)
or you can add the directory in question to your classpath:
java -cp "lib/*;lib" ...
and then use your original method.
(Unix uses : rather than ; as classpath separator)

Reading a file into compiled jar by relative path

How would you read a file into a program that's compiled into a jar next to it through its local directory? The type read would be a simple .txt file.
It depends on what the usage of the program is. Do you know how the jar is supposed to be executed? When you try to run it, does it spit out a "usage: somejar firstarg secondarg" type message?
Also, if its a jar that you've compiled and you know how it should be executed, then you may have forgot to set its main class or manifest.
Check this: http://www.mkyong.com/java/how-to-make-an-executable-jar-file/
If you want to read a file that exists within an external .jar file, you will need to unzip the .jar file first in your code and then retrieve the file. You can do this using Java's zip APIs. See this answer if this is the case: Easiest way to unpack a jar in java
If you want to read a file that is in the same .jar file that your code is executing, you can get the file as a resource. See this answer: Get a resource using getResource()
If the file is simply in the exact same directory as the executable .jar, create a new file like so:
File input = new File("myfile.txt");

Java - read file from directory for jar

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).

Eclipse unable to locate file-- FileNotFoundException on File object usage

When I attempt to access a File object in Java using Eclipse, the system sends a FileNotFoundException whenever the file is accessed. I have created the file manually and placed it within Eclipse's file browser. The file does have content, so the problem isn't that it's empty. I am initializing the File with
File file = new File(this.getClass().getResource("save.txt").toString());
and accessing it with
PrintWriter p = new PrintWriter(file);
which sends the error. The stacktrace flows back through nothing except a path of initializations that create this class. The exception is
java.io.FileNotFoundException: file:\C:\Users\Nathaniel\Downloads\ERPGE-Global%20Equestria%20Workspace\Swarm\bin\main\save.txt (The filename, directory name, or volume label syntax is incorrect)
What could be causing this error, and how can it be fixed?
You need to make sure that the resource is included in the project's build path.
You can do this in one of two ways:
Put it in a folder (e.g. "res") then add that folder to the build path. That way, all the files in the folder will be added to the build path.
Put it inside (one of) your source folders. Be aware that if you put it inside a package folder, you'll need to include the relative path to that folder (see below).
Personally I prefer option #1.
Edit: You might also find it useful to have sub-directories of the res folder. If you have a file such as res/images/button.png and you've added the res folder to the build path, you need to access the file with the string "images/button.png".
Edit 2: Fixed some misleading info.
The file needs to be placed in the parent project folder itself and not the source folder. If a file is created without a specified file path, this is where it would be stored.
Provide the actual path to the file and get the file Object. Then you can use it.
File file = new File("C:\Users\Nathaniel\Downloads\save.txt");
PrintWriter p = new PrintWriter(file);
EDIT:
Externalising the File Name:
Create a properties file filedetails.properties in the external folder/package.
fileName=C:\Users\Nathaniel\Downloads\save.txt
Accessing the resource bundle.
ResourceBundle b=ResourceBundle.getBundle("external.filedetails") ;
String fileName=b.getString("fileName");
File file=new File(fileName);

How to specify relative file path in Java file so that it can still work after the file is put in jar file?

Suppose I have a Java class that needs to access a file with absolute path
/home/gem/projects/bar/resources/test.csv:
package com.example
class Foo {
String filePath = ????? // path to test.csv
String lines = FileInputStream(new File(filePath).readAllLines();
}
Where the path to Foo.java is /home/gem/projects/bar/src/com/example.
Of course I cannot specify absolute path to the resource file. This is because jar file will be distributed as library for any clients to use in their own environments.
Assume the resource file like test.csv is always in the same path relative to project root. When a jar is created containing Foo.class, this jar also contains test.csv in the same relative path ( relative to project root).
What is the way to specify relative path that would work no matter where the project bar is moved to? Also how can I create a jar file (which can be in any location) so that the path to the resource file test.csv would still be correct.
To keep things simple, I have used invalid Java API ( readAllLines() which reads all the lines and return a string containing entire file content. Also not using try/catch).
Assume csv file can be read as well as written to.
I hope this makes it clear now.
Put the test.csv file into the src folder and use this:
Foo.class.getResourceAsStream("/test.csv")
To get an InputStream for the file. This will work wherever the project is moved, including packaged as a JAR file.
Example:
ProjectX\src\Test.java
ProjectX\resources\config.properties
If you have the above structure and you want to use your config.properties file, this is how you do it:
InputStream input = new FileInputStream("./resources/config.projects");
In this example you don't have to worry about packaging your source into jar file. You can still modify your resources folder anytime.
Use getResource(), as shown here.

Categories

Resources