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
Related
I'm developing a java swing application and it works fine, but after building my app , when I run the jar file , my app doesn't works as I want. so to know what's the problem I used this test :
FileReader reader;
Properties props;
try{
reader = new FileReader("src\\inputs.properties");
props = new Properties();
props.load(reader2);
JOptionPane.showMessageDialog(null,reader.getClass());
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage());
}
so when i run the app it works fine and i get this message :
message before building the app
And that means that my properties file is loaded.
But when I build the app, when I run it I get this message :
message after building the app
My problem is how to make my properties file works after building may app?
I'm using netbeans and this is my project structure :
-source Package
--default package
-- inputs.properties
--myapppackage
--myapppackage.java
thanks in advance.
Please create a folder "config" in your project and place the inputs.properties into it.
reader = new FileReader("config/inputs.properties");
for details, you can also go through this thread:
Netbeans FileReader FileNotFound Exception when the file is in folder?
Or:
When your resourse is in JAR file, it's not a File anymore. A File is only a physical file on the filesystem. Solution: use getResourceAsStream. Something like this:
try {
Properties props;
Property p=new Property();
InputStreamReader in=new InputStreamReader(p.getClass().getResourceAsStream("/config/" + "inputs.properties"));
props = new Properties();
props.load(in);
JOptionPane.showMessageDialog(null, in.getClass());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
Try to use this to load the file of properties:
File file = new File("inputs.properties);//use the right path
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
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 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
I'm developing a program with NetBeans 8.0 and JavaFX Scene Builder 2.0 that need store some variables in a file, where admin users can modify it when needed, (like change server IP address, or a number value from a no editable textfield) and if they close and load again the program, the changes made in variables are kept. Like any settings section of a program.
I just try do it with the Properties file, but i have problems to store it in the same folder as .jar file. When the program execute the line new FileOutputStream("configuration.properties"); the file is created at root of the disk. As the folder of the file can be stored anywhere, i not know how indicate the right path.
Creating the properties file in the package of the main project and using getClass().getResourceAsStream("configuration.properties"); i can read it but then i can not write in for change values of variables.
Is there a better method to create a configuration file? Or properties file is the best option for this case?
My other question is whether it is possible to prevent access to the contents of the file or encrypt the content?
PD: I've been testing this part of the code in Linux operating system currently, but the program will be used in Windows 7 when ready.
If you use Maven, you can store your property files in your resources folder, say resources/properties/. When you need to load them, do this:
private Properties createProps(String name)
{
Properties prop = new Properties();
InputStream in = null;
try
{
in = getClass().getResourceAsStream(name);
prop.load(in);
}
catch (IOException ex)
{
System.err.println("failed to load \"" + name + "\": " + ex);
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
System.err.println("failed to close InputStream for \"" + name + "\":\n" + FXUtils.extractStackTrace(ex));
}
}
return prop;
}
Where name is the full path to your properties file within your resources folder. For example, if you store props.properties in resources/properties/, then you would pass in properties/props.properties.
I am not 100% sure if you can carry over this exact procedure to a non-Maven project. You'd need to instruct whatever compiler tool you are using to also include your property files.
As far as your final question goes, in regards to encrypting your properties, I would consider posting that as a separate question (after having done thorough research to try to discover an existing solution that works for you).
At last i found how obtain the absolute path from folder where is .jar file to create properties file in, and read/write it. Here is the code:
File file = new File(System.getProperty("java.class.path"));
File filePath = file.getAbsoluteFile().getParentFile();
String strPath = filePath.toString();
File testFile = new File(strPath+"/configuration.properties");
Tested in Ubuntu 13.04 And Windows 7 and it works.
For encrypt the properties values i found this thread that answer how do it.
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