how to make a properties file available after building a java application - java

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();

Related

Add directory to classpath in IntelliJ

i am trying to run my main class and to add additional property files into the classpath but it does not happen. I saw some solutions like link but they do not work for me. I also tried adding "-cp \path to property files" into Run configuration -> VM options but again without success.
If I'm understanding you correctly, you'll have to create the file first if you don't want to read from the existing one, then write to it in something similar as below:
try {
File f = new File("path/to/propertyFile.properties");
if (file.createNewFile()){
// some debugging
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
// you have your file now, and you can perform manipulations to it
OutputStream output = new FileOutputStream("path/to/propertyFile.properties")
Properties prop = new Properties();
prop.setProperty("key", "value");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
}

java.io.FileNotFoundException: config.properties

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.

File not found when running jar from command line of a NetBeans project

I wrote a Java Application using NetBeans. It reads text file from the project's root directory. When I run the jar file from command line it can't find the required file.
String inputFile = "input.txt";
Properties prop = new Properties();
String targetFormat = null;
try {
InputStream input = new FileInputStream("book-info-converter.properties");
prop.load(input);
targetFormat = prop.getProperty("targetFormat");
}
catch(IOException ex){
System.out.println("file not found");
}
How to solve this problem? Where to put my file so that the application can find that when running jar from command line?
Place the book-info-converter.properties in the src folder (it's better in resources if you have). Then you can load it as resource stream like
InputStream input = YourClass.class.getResourceAsStream("/book-info-converter.properties");

Configuration File for Java Application to change path

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

Load and Save Properties from file

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

Categories

Resources