I have to read properties file "MyProperty.properties" from "ReadProp.java" class given my the following directory structure of my "war" file I am going to deploy.
MyApp.war
| ----MyProps
| |--MyProperty.properties
|---WEB-INF |
|--classes
|---ReadProp.java
I am going to deploy this "war" file in "Sun portal server". But I should not change any of this directory structure because of the requirement specification.
I am reading this file in the following way
String path = servletContext.getRealPath("/MyProps/MyProperty.properties"); System.out.println("path: " + path);
Properties prop = new Properties();
try {
prop.load(new FileInputStream(path));
);
} catch (Exception e) {
e.printStackTrace();
}
String name= prop.getProperty("name");
It is working fine. but the problem is if I change properties file after loading the application the changes are not reflecting.
I may change the properties file anytime how to do If I want that changes should be reflected . I mean the application should load the properties file everytime in the exexcutio
You won't see changes unless you bounce the app server.
A better choice would be to put the .properties file in your /WEB-INF/classes folder and read it from the CLASSPATH using getResourceAsStream().
You don't say where you're reading the code. You might have to implement a Timer task to periodically wake up and reload the .properties file.
You might also try a WatchService if you're using JDK 7:
Auto-reload changed files in Java
You need to use java 7 WatchService for that Example Link
I got the answer:
String path = servletContext.getRealPath("/MyProps/MyProperty.properties");
System.out.println("path: " + path);
Properties prop = new Properties();
try {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
prop.load(fis);
}
catch (Exception e) {
e.printStackTrace();
}
The newer way to do this is:
Path path;
try {
path = Paths.get("MyProperty.properties");
if (Files.exists(path)) {
props = new Properties();
props.load(Files.newInputStream(path));
}
} catch (IOException e) {
e.printStackTrace();
}
Related
I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.
My .properties file is in src\main\assets\userInfo.properties
Properties props = new Properties();
InputStream inputStream = null;
try{
inputStream = getBaseContext().getAssets().open("userInfo.properties");
props.load(inputStream);
props.put("name", "smith");
FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
props.store(output, "This is overwrite file");
String name = props.getProperty("name");
Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Current code throws this error:
java.io.FileNotFoundException: userInfo.properties (Read-only file system)
You can't write to the assets folder, as it is inside the APK which is read-only.
Use internal or external storage instead
You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.
I have created a java application that copies data from properties file (resources-> settings -> config.properties) and uses it. At one point the properties file values are updated and the code has to use the new values. The code works fine when executed from Netbeans. But when I execute ti from the dist folder after build, the old values get loaded everytime even when I change the the properties file. The properties file gets updated but the values used are still the old ones.
Code to write properties file
File f = new File(System.getProperty("user.dir") + "\\resources\\settings\\config.properties");
try (OutputStream output = new FileOutputStream(f)) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("xml", xmlFileTextBox.getText());
// save properties to project root folder.
prop.store(output, null);
} catch (IOException exception) {
exception.printStackTrace();
}
Code to read values in properties file
try {
Properties prop = new Properties();
String propFileName = "settings/config.properties";
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName)) {
if (inputStream != null) {
prop.load(inputStream);
xmlFileTextBox.setText(prop.getProperty("xml"));
}
inputStream.close();
}
} catch (Exception e) {
System.out.println("Exception: " + e);}
The file you are reading from is a file that is packaged with your application and not the file you are saving to.
This code, getClass().getClassLoader().getResourceAsStream(propFileName)), gives you a resource from the classpath.
You need to create the File in the same way as when you save the properties, then get the InputStream from that File.
If you want to have the defaults in your original properties file you might need to check for null in the "save file" and if it don't have data then read from your default resourse file.
Quick one. I'm trying to deploy a program, which borks at the following code. I want to read a properties file named, adequately, properties.
Properties props = new Properties();
InputStream is;
// First try - loading from the current directory
try {
File f = new File("properties");
is = new FileInputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(System.err);
is = null;
}
try {
if (is == null) {
// Try loading from classpath
is = getClass().getResourceAsStream("properties");
}
//Load properties from the file (if found), else crash and burn.
props.load(is);
} catch (IOException e) {
e.printStackTrace(System.err);
}
Everything goes well when I run the program through Netbeans.
When I run the JAR by itself, though, I get two exceptions.
java.io.FileNotFoundException: properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
.
.
.
Exception in Application start method
Exception in Application stop method
java.lang.reflect.InvocationTargetException
.
.
.
(exception during props.load(is) because is == null)
I'm running the file from the "dist" folder. I've tried placing the properties file inside the folder with the jar, without result. Normally, the properties file is located in the root project folder.
Any ideas?
You read your file as a resource (getResourceAsStream("properties");). So it must be in the classpath. Perhaps in the jar directly or in a directory which you add to the classpath.
A jar is a zip file so you can open it with 7zip for example add your properties file to the jars root level and try it again.
Thanks to the comments, I built an absolute path generator based on the current run directory of the jar. Props to you, guys.
private String relativizer(String file) {
URL url = RobotikosAnomologitos.class.getProtectionDomain().getCodeSource().getLocation();
String urlString = url.toString();
int firstSlash = urlString.indexOf("/");
int targetSlash = urlString.lastIndexOf("/", urlString.length() - 2) + 1;
return urlString.substring(firstSlash, targetSlash) + file;
}
So my new file-reading structure is:
Properties props = new Properties();
InputStream is;
// First try - loading from the current directory
try {
File f = new File("properties");
is = new FileInputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(System.err);
is = null;
}
try {
if (is == null) {
// Try loading from classpath
String pathToProps = relativizer("properties");
is = new FileInputStream(new File(pathToProps));
//is = getClass().getResourceAsStream(pathToProps);
}
//Load properties from the file (if found), else crash and burn.
props.load(is);
} catch (IOException e) {
e.printStackTrace(System.err);
}
// Finally parse the properties.
//code here, bla bla
I am trying to load properties file. Here is my structure
Now i am trying to load test.properties file. But i am getting null. Here how i am doing
public class Test {
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File temp = new File(workingDir + "\\" + "test.properties");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
Properties properties = null;
try {
properties = new Properties();
InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream(absolutePath);
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
} //end of class Test
This program prints
Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
But it is not loading properties file from this path. Although it is present there. Why i am getting null ?
Thanks
Edit---
----------------------------
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File temp = new File(workingDir, "test.properties");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
try {
properties = new Properties();
InputStream resourceAsStream = new FileInputStream(temp);
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
java.io.FileNotFoundException: D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.softech.ls360.integration.BatchImport.main(BatchImport.java:57)
Oh oh ... There are several problems here:
1) In your first provided code snippet, you are using a ClassLoader for loading a resource file. This is indeed a good decision. But the getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path.
2) Your second code snippet (after edit) results in not being able to find the file "D:...\LS360BatchImportIntegration\test.properties". According to your screenshot, the file should be "D:...\LS360AutomatedRegulatorsReportingService\test.properties". This is another directory.
I fear, that your descriptions are not up to date with the findings on your machine.
But let's just move to a reasonable solution:
1) In your Eclipse project (the screenshot tells us, that you are using Eclipse), create a new directory named "resources" in the same depth as your "src" directory. Copy - or better move - the properties file into it.
2) This new directory must be put into the "build path". Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder". Note: This build path will be the class path for the project, when you run it.
3) As the resources directory now is part of your class path and contains your properties file, you can simply load it with getResourceAsStream("test.properties").
EDIT
I just see, that you also use Maven (the pom.xml file). In Maven, such a resources directory exists by default and is part of the build path. It is "src/main/resources". If so, just use this.
Please put your property file in /src/main/resources folder and load from ClassLoader. It will be fix.
like
/src/main/resources/test.properties
Properties properties = null;
try {
properties = new Properties();
InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream("test.properties");
if (resourceAsStream != null) {
properties.load(resourceAsStream);
}
} catch (IOException e) {
e.printStackTrace();
}
You are using the class loader (which reads in the classpath) whereas you are using the absolute path.
Simply try:
InputStream resourceAsStream = new FileInputStream(temp);
As a side note, try instanciating your file doing:
File temp = new File(workingDir, "test.properties");
to use the system-dependent path spearator.
I had a similar problem with a file not being found by getResourceAsStream(). The file was in the resources folder (src/main/resources), and still not found.
The problem got resolved when I went into the eclipse Package Explorer and "refreshed" the resources folder. It was in the directory, but Eclipse did not see it until the folder was refreshed (right-click on the folder and select Refresh).
I hope this helps !!
You can keep your test.properties into src/main/resources
public static Properties props = new Properties();
InputStream inStream = Test.class.getResourceAsStream("/test.properties");
try {
loadConfigurations(inStream);
} catch (IOException ex) {
String errMsg = "Exception in loading configuration file. Please check if application.properties file is present in classpath.";
ExceptionUtils.throwRuntimeException(errMsg, ex, LOGGER);
}
public static void loadConfigurations(InputStream inputStream) throws IOException{
props.load(inputStream);
}
You're passing a file path to getResourceAsStream(String name), but name here is a class path, not a file path...
You could make sure the file is on your classpath, or use a FileInputStream instead.
I want to write into a *.properties file. Thats my code how I do this:
properties = loadProperties("user.properties");//loads the properties file
properties.setProperty(username, password);
try {
properties.store(new FileOutputStream("user.properties"), null);
System.out.println("Wrote to propteries file!" + username + " " + password);
I do not get an exception, but I also do not get the output written into the file.
Here is also my file-structure:
I appreciate your answer!!!
UPDATE
I load my properties file with:
InputStream in = ClassLoader.getSystemResourceAsStream(filename);
My question is, how to load it from a specific path?
Here is my "new" File Structure:
Here is my testing code:
#Test
public void fileTest() throws FileNotFoundException, IOException {
File file = null;
Properties props = new Properties();
props.setProperty("Hello", "World");
URL url = Thread.currentThread().getContextClassLoader()
.getResource("exceptions/user.properties");
try {
file = new File(url.toURI().getPath());
assertTrue(file.exists());
} catch (URISyntaxException e) {
e.printStackTrace();
}
props.store(new FileOutputStream(file), "OMG, It werks!");
}
It does creates and rewrites a file in my target/classes/exceptions directory (in a maven/eclipse proyect) so I guess it really works, but of course that is not tested in a JAR file.
Here is the file:
#OMG, It werks!
#Sat Nov 10 08:32:44 CST 2012
Hello=World
Also, check this question: How can i save a file to the class path
So maybe what you want to do never will work.