How to access property file in user.home directory? - java

How can I access a property file called test.property in user.home?
This doesn't work:
public class Properties {
private static java.util.Properties p = new java.util.Properties();
static {
try {
String home = System.getProperty("user.home");
home += "\\test.properties";
System.out.println("User home: " + home);
InputStream is = Properties.class.getResourceAsStream(home);
p.load(is);
} catch (FileNotFoundException e) {
System.out.println("property file could not be found!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

File propsFile = new File(home, "test.properties");
InputStream is = new FileInputStream(propsFile);
You will probably find that the user.home is not on the run-time class-path of the application. In that case, use a File instead.

Related

Property file is returning as null in Java

I am trying to read some property from the properties file, but my code is not reading the property file. The properties file is in some folder in my machine.
Here is my code:
public String getproperty(){
String extension="";
Properties prop = new Properties ();
String propname = "\\"+Any location in your machine+"\\fileExtension.properties";
Logger.debug("ReadFiles", " ----Property file path---- "+ propname, null);
ip = getClass().getClassLoader().getResourceAsStream(propname);
Logger.debug("ReadFiles", " ----ip value ---- "+ip, null);
try {
if(ip != null){
prop.load(ip);
Logger.debug("ReadFiles", " ----Property file loaded---- ", null);
}
extension = prop.getProperty("fileExt");
Logger.debug("ReadFiles", " ----Property = " + extension, null);
} catch (IOException e) {
Logger.error("ReadFiles", " ----Error while loading property file---- ", null);
e.printStackTrace();
}
finally{
try {
ip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return extension;
}
I am creating a jar placing it in lib folder of server (installed in my machine) and placing the properties file in my machine and given the same path in code. I have tried with absolute path and without absolute path.
Please try this example that uses an absolute path to the properties file.
package com.company;
import java.io.*;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("/home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties");
prop.load(input);
String extension = prop.getProperty("fileExt");
System.out.println("ReadFiles ----Property = " + extension);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Test
cat /home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties
#Mon Dec 26 17:31:30 CET 2016
dbpassword=password
database=localhost
dbuser=foobar
fileExt=.xml⏎
Run the program
ReadFiles ----Property = .xml

Text document is becoming file folder

Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java eclipse error with exported runnable jar file

I have a problem with an exported jar file. When I run my project in Eclipse it runs fine, but when I run it as an exported jar from the console I receive the following error message:
java.io.FileNotFoundException: firstLaunch.properties (System can't find file)
or
java.io.FileNotFoundException: resources/config/firstLaunch.properties (System can't find file)
I tried to put it in to the resource folder and change syntax from firstLaunch.properties to /resource/config/firstLaunch.properties, but again it says the same thing but with a different path. I don't know why is this doing this.
Here is the code:
public void saveConfigFile(String file, String key, String value) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(file);
// set the properties value
prop.setProperty(key, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My syntax for executing the method is
if (properties.loadConfigFile("firstLaunch.properties", "value").equals(properties.loadConfigFile("true.properties", "true"))) {
properties.saveConfigFile("port.properties", "port", "8795");
properties.saveConfigFile("ip.properties", "ip", temp[1]);
properties.saveConfigFile("firstLaunch.properties", "value", "false");
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
} else {
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
}
Your problem probably has to do with how you are referencing the file location. Add some detail/code examples as to how you are referencing the code, so then we can be sure to help. Having said that here is another way to reference a properties file:
Put it in the classpath like this:
private static Properties prop = new Properties();
private static String filename = "<name of file>.properties";
InputStream input = <ClassName>.class.getClassLoader().getResourceAsStream(filename);
try {
if (input==null) {
loggerOut.log(Level.SEVERE, "Sorry, unable to find " + filename);
}
prop.load(input);
loggerOut.info("XML In storage path: " prop.getProperty("<property in file>"));
fileNameAndPath = prop.getProperty("fileNameAndPathIN").trim();
logNameAndPath = logPath + logName;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input!=null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Update properties file values with form values

I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();
here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.

Unable to read properties file after creating it

I am creating a properties file and putting into my classpath folder Resources.
When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now.
My class file is as follows :
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
PrintWriter output = null;
try {
output = new PrintWriter("Resources/config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
if(output!=null) {
System.out.println("Output");
output.close();
}
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
Properties prop1 = new Properties();
BufferedInputStream input = null;
try {
String filename = "config.properties";
input = (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop1.load(input);
//get the property value and print it out
System.out.println(prop1.getProperty("database"));
System.out.println(prop1.getProperty("dbuser"));
System.out.println(prop1.getProperty("dbpassword"));
if(input!=null) {
System.out.println("Input");
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please help.
When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values. You are looking for an implementation like ReloadableResourceBundleMessageSource

Categories