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();
}
Related
My project structure looks like below. I do not want to include the config file as a resource, but instead read it at runtime so that we can simply change settings without having to recompile and deploy. my problem are two things
reading the file just isn't working despite various ways i have tried (see current implementation below i am trying)
When using gradle, do i needto tell it how to build/or deploy the file and where? I think that may be part of the problem..that the config file is not getting deployed when doing a gradle build or trying to debug in Eclipse.
My project structure:
myproj\
\src
\main
\config
\com\my_app1\
config.dev.properties
config.qa.properties
\java
\com\myapp1\
\model\
\service\
\util\
Config.java
\test
Config.java:
public Config(){
try {
String configPath = "/config.dev.properties"; //TODO: pass env in as parameter
System.out.println(configPath);
final File configFile = new File(configPath);
FileInputStream input = new FileInputStream(configFile);
Properties prop = new Properties()
prop.load(input);
String prop1 = prop.getProperty("PROP1");
System.out.println(prop1);
} catch (IOException ex) {
ex.printStackTrace();
}
}
Ans 1.
reading the file just isn't working despite various ways i have tried
(see current implementation below i am trying)
With the location of your config file you have depicted,
Change
String configPath = "/config.dev.properties";
to
String configPath = "src\main\config\com\my_app1\config.dev.properties";
However read the second answer first.
Ans 2:
When using gradle, do i needto tell it how to build/or deploy the file
and where? I think that may be part of the problem..that the config
file is not getting deployed when doing a gradle build or trying to
debug in Eclipse.
You have two choices:
Rename your config directory to resources. Gradle automatically builds the resources under "src/main/resources" directory.
Let Gradle know the additional directory to be considered as resources.
sourceSets {
main {
resources {
srcDirs = ["src\main\config\com\my_app1"]
includes = ["**/*.properties"]
}
}
}
reading the file just isn't working despite various ways i have tried (see current implementation below i am trying)
You need to clarify this statement. Are you trying to load properties from an existing file? Because the code you posted that load the Properties object is correct. So probably the error is in the file path.
Anyway, I'm just guessing what you are trying to do. You need to clarify your question. Is your application an executable jar like the example below? Are trying to load an external file that is outside the jar (In this case gradle can't help you)?
If you build a simple application like this as an executable jar
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[]args) {
File configFile = new File("test.properties");
System.out.println("Reading config from = " + configFile.getAbsolutePath());
FileInputStream fis = null;
Properties properties = new Properties();
try {
fis = new FileInputStream(configFile);
properties.load(fis);
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException e) {}
}
}
System.out.println("user = " + properties.getProperty("user"));
}
}
When you run the jar, the application will try to load properties from a file called test.properties that is located in the application working directory.
So if you have test.properties that looks like this
user=Flood2d
The output will be
Reading config from = C:\test.properties
user = Flood2d
And that's because the jar file and test.properties file is located in C:\ and I'm running it from there.
Some java applications load configuration from locations like %appdata% on Windows or /Library/Application on MacOS. This solution is used when an application has a configuration that can change (it can be changed by manually editing the file or by the application itself) so there's no need to recompile the application with the new configs.
Let me know if I have misunderstood something, so we can figure out what you are trying to ask us.
Your question is slightly vague but I get the feeling that you want the config files(s) to live "outside" of the jars.
I suggest you take a look at the application plugin. This will create a zip of your application and will also generate a start script to start it. I think you'll need to:
Customise the distZip task to add an extra folder for the config files
Customise the startScripts task to add the extra folder to the classpath of the start script
The solution for me to be able to read an external (non-resource) file was to create my config folder at the root of the application.
myproj/
/configs
Doing this allowed me to read the configs by using 'config/config.dev.properies'
I am not familiar with gradle,so I can only give some advices about your question 1.I think you can give a full path of you property file as a parameter of FileInputStream,then load it using prop.load.
FileInputStream input = new FileInputStream("src/main/.../config.dev.properties");
Properties prop = new Properties()
prop.load(input);
// ....your code
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 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
FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");
Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.
Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:
File file = new File("member.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("test");
} catch (IOException e) {
e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
Closing is mandatory since it flushes the written data into the file and releases the file lock.
Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.
If the file is successfully created (no exception is raised), it is in the current working directory.
For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."
In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.
In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.
It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.
If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).
You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.