In my spring project, I have in my classpath a file named database.properties with the following content:
jdbc.Classname=org.postgresql.Driver
jdbc.url=
jdbc.user=
jdbc.pass=
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate
I have a method in one of my service classes where I manually export the database schema to server through hibernate. The code for this method in this moment is this:
public void create_tables(String maquina, String usuario, String senha) {
Configuration config = new Configuration();
SchemaExport schema = new SchemaExport(config);
schema.create(true, true);
}
I want load the properties from file database.properties in my config variable, set up the values I pass to the method in this variable (url, user and pass), and save this new configuration in the same file.
Anyone can point the direction to do that?
does this do it?
Properties props = new Properties();
FileInputStream fis = new FileInputStream( "database.properties" );
props.load( fis );
fis.close();
props.setProperty("jdbc.url", {{urlvalue}} );
props.setProperty("jdbc.user", {{user value}} );
props.setProperty("jdbc.pass", {{pass value}} );
FileOutputStream fos = new FileOutputStream( "database.properties" );
props.store( fos );
fos.close();
I have in my classpath a file named database.properties
I want load the properties from file database.properties in my config variable, set up the values I pass to the method in this variable (url, user and pass), and save this new configuration in the same file.
This is at least difficult, and maybe impossible.
The "file" you are trying to update may not be a file at all. It might be a component of a larger JAR or ZIP file. It may be an in-memory or on-disk cache of something that was downloaded. It might (hypothetically) have been encrypted using a public/private key ... for which we don't have the "encrypt" key.
In addition to being difficult, it is a bad idea. Suppose that the your service is deployed as a WAR file, and that the properties file is delivered in the WAR. You modify the properties ... and so on. Then, for some reason you redeploy the WAR. This will overwrite your configuration.
If you want the configuration properties to be updatable, they should not be on the classpath. Put the file into a separate directory (outside of the webapp tree ...) and access it via a file pathname or file: URL.
I try remove the classpath:, but I face the error Caused by: java.io.FileNotFoundException: class path resource [database.properties] cannot be opened because it does not exist
It looks like you are using an (incorrect) relative path for the properties file.
Copy the file to (say) "/tmp/database.properties", change the annotation to
#PropertySource("/tmp/database.properties")
and see if that works. If it does, then you can figure out a more appropriate place to store the file. But as I said above, if you try to update a file in your webapp directory, there's a good chance it will get clobbered when you redeploy. So don't put it there.
Example load props from file.
We have test config file with filename = conf.props
Contains:
key0=value0
key1=value1
Next class load properties in the application:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class LogProcessor {
public void start(String fileName ) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(fileName);
prop.load(fis);
System.out.println (prop.getProperty("key0"));
}
}
How to run:
public static void main(String[] args) {
try {
new LogProcessor().start();
} catch (IOException e) {
e.printStackTrace();
}
Return value0
\|/ 73
Related
I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.
I have made a Java (.jar) application that uses and external image and MS Access database.
Both things are accessed using a path. This won't work if I give the application to my friend to test as the path wont match.
I was wondering if I could make configuration settings file that would change the path by editing the settings file and make the application work fine instead of opening the source code in editor and editing there.
Yes you can do it by creating a configuration file. Lets say your configuration file is "config.properties". You can mention properties required in file like
#comment
imageFile=C://imagePath
database=<path to db>
username=
password=
Then read the file
Properties properties = new Properties();
InputStream in = null;
in= new FileInputStream("config.properties");
//load a properties file
properties.load(input);
// get the property value and print it out
System.out.println(properties.getProperty("imageFile"));
---
Make sure file is accessible by keeping it in classpath.
Properties properties;
try(InputStream input = this.getClass().getClassLoader().getResourceAsStream("app.properties")) {
properties = new Properties();
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(properties.getProperty("my.path"));
Property file format is very simple
my.path = /home/file.txt
semicolon_Also_delimiter:value
semicolon\:can\:be\:escaped:value
I am trying to use a properties file to store my DB connection details. It worked when I created a Java application and gave the file name as it is since I placed the properties file in the project root folder.
However, I get a FileNotFoundException when I try this in my Web application. I created a res directory under the project node to hold the properties file. I then gave the path as "res/db.properties" but I get the exception. I also tried placing this file under the configuration files directory but still got the same exception.
Here is my code -
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
/**
*
* #author aj
*/
public class getConfigValues {
public String[] getPropValues() {
String[] props = new String[4];
try {
Properties prop = new Properties();
String propFileName = "res/db.properties";
InputStream input = null;
input = new FileInputStream(propFileName);
prop.load(input);
props[0] = prop.getProperty("dbURL");
props[1] = prop.getProperty("driverClass");
props[2] = prop.getProperty("user");
props[3] = prop.getProperty("password");
return props;
} catch (FileNotFoundException ip) {
props[0] = "not found";
return props;
} catch (IOException i) {
props[0] = "IO";
return props;
}
}
}
What am I doing wrong here?
As a web application you have no way of predicting the current working directory, so using a relative path will always be problematical;
Depending upon how you web application is packaged, your property file may not even be a file system object. It may well be a resource buried in a .war file.
One reliable way for you to access this file is to build it into your web app's WEB-INF directory. You can then access it using javax.servlet.ServletContext.getResourceAsStream("WEB-INF/res/db.properties").
Alternatively, you could build it into the WEB-INF/classes directory and load it using java.lang.ClassLoader.getResourceAsStream("/res/db.properties").
Most likely the current directory is different when you run it as a web app... There is a System property that will tell you what the current directory is. Or you can use Class.getResource to use your classpath to find the res directory
Your main mistake is trying to load a resource with file-related classes. Property files are resources to the application and thus should be placed relatively to this application.
"Relatively" means "in the class path".
In a standalone application, simply assure to mention the directory of those resources as part of the class path. In a web application, the directory WEB-INF/classes is already part of the application's class path.
Now comes the second part of the answer: How to load such resources? Simply: With a ClassLoader. Its responsibility is not only to load classes but also to load resources (such as property files).
Go with that (exception handling omitted):
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL resourceUrl = loader.getResource("res/db.properties");
Properties properties = new Properties();
try(InputStream input = resourceUrl.openStream()) {
properties.load(input);
}
String[] result = new String[4];
...
return result;
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
The directory structure of my application is as follows:-
My App
++++++ src
++++++++com
++++++++++readProp.java
++++++++resource
++++++++++message.properties
I am trying to read the file as follows:-
public Static final string FilePath="resource.message.properties"
Here the code to read the file. I tried using the following two techniques but to no use...
File accountPropertiesFile = new File(FacesContext.getCurrentInstance()
.getExternalContext().getRequestContextPath()
+ FilePath);
properties.load(externalContext.getResourceAsStream(FilePath));
But none yeild any sucess while reading through the Bean class. please help...
Your properties file is in the classpath. The java.io.File only understands the local disk file system structure. This is not going to work. You need to get it straight from the classpath by the classloader.
Here's a kickoff example:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/messages.properties");
if (input != null) {
Properties properties = new Properties();
try {
properties.load(input);
} finally {
input.close();
}
}
I don't know if this is your problem, but you should try using slashes instead of periods, since they're stored as actual folders in the filesystem.