Update property using Properties - java

I want to add new property to an existing file. Whenever, I add the new property, the entire file gets overwritten. Is there a way to update the file and not overwrite property.
FileOutputStream fo = new FileOutputStream(PROPERTIES_FILE);
Properties pr = new Properties();
pr.setProperty("Key1", "KeyValue");
try {
pr.store(fo, " Comments");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(1) Now if I want to add a new property called Key2 and the set a value KeyValue2. Is it possible ?
(2) Also when I deploy in tomcat, only when I give the absolute path, the file is getting updated. Is there a way to find the file location at runtime. Because when I run test case, the file will be present locally and the path will be different.
(3) Is there a way to leverage classpath in anyway for this.
Thanks in advance!

**I am writing it down since I did not find clear answer for the problem mentioned **
(1) Now if I want to add a new property called Key2 and the set a value KeyValue2. Is it possible ?
**Yes it is possible. The key to understanding here is that, the properties object will be store on calling 'store' api. Here appending does not happens. The file will be overwritten by the contents of the properties object. THE API DOES NOT SUPPORT APPENDING IT.
The solution this problem will be to :
1) Load the properties from the same file
2) Update the new property or existing property
3) then store using the output stream
IN THIS WAY THE CONTENT OF THE FILE WILL NOT BE LOST**
(2) Also when I deploy in tomcat, only when I give the absolute path, the file is getting updated. Is there a way to find the file location at runtime. Because when I run test case, the file will be present locally and the path will be different.
** There are two ways to do it
1) Make sure that the file is present in the classpath. If present in the classpath, we need not give absolute path before the filename
2) Provide another class which set the path. In this way, the path can be set when running the testcases. (TESTNG/JUNIT)**
(3) Is there a way to leverage classpath in anyway for this.
** Already covered above **
Hope this helps

Related

Android get file using path (in String format)

My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders

File not found exception with external files

Hi i have made a small program that reads a config file. This file is stored outside the actual jar file. On the same level as the jarfile actually.
When i start my program from a commandline in the actual directory (ie. D:\test\java -jar name.jar argument0 argument1) in runs perfectly.
But when i try to run the program from another location then the actual directory i get the filenotfound exception (ie. D:\java -jar D:\test\name.jar argument0 argument1).
The basic functionality does seem to work, what am i doing wrong?
As requested a part of the code:
public LoadConfig() {
Properties properties = new Properties();
try {
// load the properties file
properties.load(new FileInputStream("ibantools.config.properties"));
} catch (IOException ex) {
ex.printStackTrace();
} // end catch
// get the actual values, if the file can't be read it will use the default values.
this.environment = properties.getProperty("application.environment","tst");
this.cbc = properties.getProperty("check.bankcode","true");
this.bankcodefile = properties.getProperty("check.bankcodefile","bankcodes.txt");
} // end loadconfig
The folder looks like this:
This works:
This doesn't:
The jar doesn't contain the text file.
When reading a File using the String/path constructors of File, FileInpustream, etc.. a relative path is derived from the working directory - the directory where you started your program.
When reading a file from a Jar, the file being external to the jar, you have at least two options :
Provide an absolute path: D:/blah/foo/bar
Make the directory where your file is located part of the class path and use this.getClass().getClassLoader().getResourceAsStream("myfile")
The latter is probably more appropriate for reading configuration files stored in a path relative to the location of your application.
There could be one more possibility:
If one part of your code is writing the file and another one is reading, then it is good to consider that the reader is reading before the writer finishes writing the file.
You can cross check this case by putting your code on debug mode. If it works fine there and gives you FileNotFoundException, then surely this could be the potential reason of this exception.
Now, how to resolve:
You can use retry mechanism something similar to below code block
if(!file..exists()){
Thread.sleep(200);
}
in your code and change the sleep value according to your needs.
Hope that helps.!!

Java - Properties failing to load, but storing properly

I need a configuration file (Properties) for this project I'm working on.
The issue is that the Properties instance fails to load from the file (no exceptions, no visible problems) although it can store properly.
Because I have a defaults HashMap, any property that doesn't exist has it's default value placed in the Properties instance, which then stores everything, so that new properties are seamlessly added when the production server is updated.
I've been tracking this bug for hours, and I can't fix it. I've read dozens of questions here on StackOverflow as well as code examples on other sites. Nothing helped.
The one reason I haven't dropped it already and used the DB instead is that the JDBC driver URL, user and password are stored in that file as well. Notice that the file is being read and written to the hard drive.
Since the defaults system puts stuff in place, even if the file doesn't exist when I try to read, after it's saved it appears, but the next run still won't read anything. I noticed the bug after I changed a setting, and checked the file after a few runs, and to my shock, all values were default.
What's currently happening is the following:
1) No matter if the file is there or not, Properties will not load anything.
2) Since there's nothing in the Properties instance, it is filled with defaults.
3) The instance will now save, overwriting the file with the default values.
Here's all the relevant code:
private static Properties getConfig(){
Properties properties = new Properties();
File cfgFile = new File("data/titallus.properties");
try{
if(cfgFile.createNewFile()){
System.out.println("Config file not found. A default config file will be created automatically.");
}
FileReader reader = new FileReader(cfgFile);
FileWriter writer = new FileWriter(cfgFile);
properties.load(reader);
reader.close();
System.out.println(properties); // Debug, always prints '{}'
for(String k : defaults.keySet()){
if(!properties.containsKey(k)){
properties.setProperty(k, defaults.get(k));
}
}
properties.store(writer, "Titallus Configuration File");
writer.close();
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
return properties;
}
I have tried everything I could think of, to no avail.
I also have a Properties subclass for multi-language support, which works just fine.
Does anyone have any idea how to fix this, or at least, another approach to this?
FileWriter writer = new FileWriter(cfgFile);
will be erasing your file before you read from it.
You create a FileWriter for the file before you load the file, which clears the existing data.

Java, how to check the existence of file

I have this small code
File source;
if ( !source.exists() ) {
source = new File("instances/student"+student.getStudentID()+".data");
}
The problem is, source is not initialized. Since the whole point is to check if it exists, how do I avoid this?
Create a File object.
File source = new File(...);
What constructor you use depends on how you want to locate a file. A simple path String could be enough.
EDIT: just realized the source of your confusion may be that you think creating the File object will try to locate the file or create it on the file system. That's not the case. Just calling new File(...) won't check its existence or try to create it. A File object is simply an abstraction for a path in your file system. It could be a directory as well.
You can do:
File f = new File(somepathhere);
if ( !f.exists() ) {
f = new File("instances/student"+student.getStudentID()+".data");
}
Or you can check if f.isFile()
You seem to have a misunderstanding. Creating a File doesn't create a file on the file system. A File object only really represents a filename. If you want to see whether a file exists, create a File of the appropriate name and check exists().
But then if you want to overwrite or append to a file you don't even need all that. Just create a new FileOutputStream(...), with the append parameter set to true if you want to append. No need to check beforehand, in fact it is more than a waste of time.

jface.preference.FileFieldEditor can't specify a new file

I'm setting up a series of preferences in my Eclipse (3.5.2) application and I'm having a problem with the FileFieldEditor. I want to allow the user to specify a log file to print output to. Often, this will be a new file. But when I use the file select dialog with FileFieldEditor, it complains that the file doesn't exists ("Value must be an existing file"). Is there a way, without extending the FileFieldEditor class, to suppress this error and have Java create that file if it doesn't exist? Thanks!
When I look the source code of org.eclipse.jface.preference.FileFieldEditor, the only solution would be to extend it and write your own version of a FileFieldEditor, with:
an overwritten changePressed() method in order to keep the file path even if the file does not exists
an overwritten checkState() method in order to avoid that error message.
So I do not see a way to avoid that FileFieldEditor extension here.

Categories