Property file in java - java

I want read property file in my java class.
for this i have written:
try {
Properties property = new Properties();
property .load(new FileInputStream("abc.properties"));
String string = property.getProperty("userName");
} catch (Exception e) {
e.printStackTrace();
}
i have placed my abc.properties file in same package where my java class resides. But i am getting FileNotFound exception.
Please let me know how to give path of property file.
Thanks and Regards

The FileInputStream will look for the file in your program's "working directory", not in the same package as your class.
You need to use getClass().getResourceAsStream("abc.properties") to load your properties file from the same package.

If the properties files is next to your class file, you should not use FileInputStream, but Class.getResourceAsStream.
property.load(getClass().getResourceAsStream("abc.properties"));
This will even work when you package everything up as a jar file.

You are better off using ClassLoader.getResourceAsStream. See this article.

let say ur class is TestClass then ur code must change to ,
InputStream input = TestClass.class.getResourceAsStream("abc.properties");
property.load(input);

Related

Can I get properties defined in "gradle.properties" in JAVA STATEMENT?

I defined a property in gradle.properties file like below:
user.password=mypassword
Can I use it as a variable value in my java statement?
Yes you can, however this is not a good idea nor a good practice. gradle.properties file is meant to keep gradle's properties itself, e.g. JVM args used at build time.
If you need to store user/pass pair in properties file, it should be placed under src/main/resources or other appropriate folder and separate from gradle.properties.
Side note: Not sure if keeping properties file in mobile application is safe in general.
You would have to read the properties file and extract the property first.
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("gradle.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("user.password"));
} catch (IOException ex) {
ex.printStackTrace();
}
You can find the detailed tutorial here

How to read properties file inside jar?

I have a config.properties file under the package com.abc.properties. From one of the java class present in com.abc.util, I need to read the property file. Both the files are present inside jar.
I have tried using
fs = new FileInputstream(VerifyFolderStructure.class.getResourceAsStream("com/abc/properties/config.properties"));
But it doesn't seem to work. Please help.
P.S: VerifyFolderStructure is my java class from which I need to load the properties file.
To obtain the stream you don't need FileInputStream at all. You can get the properties' file stream like this
InputStream is = VerifyFolderStructure.class.getResourceAsStream("/com/abc/properties/config.properties");
I think you need to add "/" in the front of you path.if you don't add "/" that means the properties is located in the same packages path as VerifyFolderStructure class.

Write to a .txt file in a package

I would like to write to a .txt file that is inside a package. I can get it to read from the exact location the .txt file is stored but not from inside the package. I'm assuming it is using class loaders but I cannot seem to get it to work.
Here is what I have so far.
public void writeFile(String fileLocation) {
Writer output = null;
File file = new File(fileLocation);
try {
output = new BufferedWriter(new FileWriter(file));
output.append("WRITING TEST");
output.close();
} catch (IOException ex) {
System.out.println("Couldn't write to file.");
}
}
Then I use this in another class to write.
WriteFile writeFile = new WriteFile();
writeFile.writeFile("src/com/game/scores.txt");
I understand that if using class loaders you remove "src/" because that will no longer exist when the program is compiled in a .jar.
It is not possible to write or update a file inside jar. Since jar itself is a file.
Please refer this link.
Write To File Method In JAR
You could use a class in that package to give you the location of the folder.
Try something like
public URL getPackageLocation() {
return getClass().getResource(".");
}
This should give you the location of the folder from which this method is being called from.
From the comments you already know that you cann't write to a file, which resides in a JAR file. At best what you can do, is creating your file, relative to the path where the JAR is located like bellow:
mylocation
|-- my-jar.jar
|-- com
|--game
|--myfile.txt
I would like to write to it to update the scores in my game as the
user goes through the levels.
While it might be possible to write to the JAR file, I don't recommend it for this use case. Just write it somewhere at:
Path userdir = Paths.get(System.getProperty("user.home"), ".myApp", "<my app version>");
You can't write into Jar file. Writing into Jar file is not recommendable. You can write outside the jar file.
Please refer this and this stack overflow question for more details.

JAVA: FileInputStream and FileOutputStream

I have this strange thing with input and output streams, whitch I just can't understand.
I use inputstream to read properties file from resources like this:
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream( "/resources/SQL.properties" );
rop.load(in);
return prop;
It finds my file and reds it succesfully. I try to write modificated settings like this:
prop.store(new FileOutputStream( "/resources/SQL.properties" ), null);
And I getting strange error from storing:
java.io.FileNotFoundException: \resources\SQL.properties (The system cannot find the path specified)
So why path to properties are changed? How to fix this?
I am using Netbeans on Windows
The problem is that getResourceAsStream() is resolving the path you give it relative to the classpath, while new FileOutputStream() creates the file directly in the filesystem. They have different starting points for the path.
In general you cannot write back to the source location from which a resource was loaded, as it may not exist in the filesystem at all. It may be in a jar file, for instance, and the JVM will not update the jar file.
May be it works
try
{
java.net.URL url = this.getClass().getResource("/resources/SQL.properties");
java.io.FileInputStream pin = new java.io.FileInputStream(url.getFile());
java.util.Properties props = new java.util.Properties();
props.load(pin);
}
catch(Exception ex)
{
ex.printStackTrace();
}
and check the below url
getResourceAsStream() vs FileInputStream
Please see this question: How can I save a file to the class path
And this answer https://stackoverflow.com/a/4714719/239168
In summary: you can't always trivially save back a file your read from the classpath (e.g. a file in a
jar)
However if it was indeed just a file on the classpath, the above answer has a nice approach

How I can specify directories in war file?

I am new to servlet . I use the following code in servlet.then deployed to Jboss 4.1 . backup_database_configuration_location is location of properties file.But it can't be find. how I can specify directories in war file ?
Thanks all in advance
try {
backupDatabaseConfiguration = new Properties();
FileInputStream backupDatabaseConfigurationfile = new FileInputStream(backup_database_configuration_location));
backupDatabaseConfiguration.load(backupDatabaseConfigurationfile);
backupDatabaseConfigurationfile.close();
} catch (Exception e) {
log.error("Exception while loading backup databse configuration ", e);
throw new ServletException(e);
}
If it is placed in the webcontent, then use ServletContext#getResourceAsStream():
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));
The getServletContext() method is inherited from HttpServlet. Just call it as-is inside servlet.
If it is placed in the classpath, then use ClassLoader#getResourceAsStream():
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.properties");
The difference with Class#getResourceAsStream() is that you're not dependent on the classloader which loaded the class (which might be a different one than the thread is using, if the class is actually for example an utility class packaged in a JAR and the particular classloader might not have access to certain classpath paths).
Where is your properties file located? Is it directly somewhere in your hard drive, or packaged in a JAR file?
You can try to retrieve the file using the getResourceAsStream() method:
configuration = new Properties();
configuration.load(MyClass.class.getResourceAsStream(backup_database_configuration_location));
(or course, replace MyClass by your current class name)

Categories

Resources