Java Properties File appending new values - java

I have an application that implements a JTree and populates the tree with a java properties file as default; The nodes are the keys and the values are the contents of the node. The application was designed to be dynamic so a JButton and JTextField are implemented to take in new values and put the values in the exists keys in the properties file.
So for example I have the line below as a default value in a sample.properties file
node=cat,dog,mice
and using the JTextField and JButton I input "rabbit" to append to the node, to look like:
node=cat,dog,mice,rabbit
I've implemented JTextField and JButton and have them working but I just can't seem to find a good way to append new values to existing keys in the properties file.

Just FileWriter
FileWriter fileWritter = new FileWriter("example.properties", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append("PROPERTES_YOUR_KEY=PROPERTES_YOUR_VALUE");
bufferWritter.close();
Update
Properties API does not support, I am not sure why you need this functionality.
You can try as below :
example.properties
PROPERTIES_KEY_3=PROPERTIES_VALUE_3
PROPERTIES_KEY_2=PROPERTIES_VALUE_2
PROPERTIES_KEY_1=PROPERTIES_VALUE_1
Program
Properties pop = new Properties();
pop.load(new FileInputStream("example.properties"));
pop.put("PROPERTIES_KEY_3", "OVERWRITE_VALUE");
FileOutputStream output = new FileOutputStream("example.properties");
pop.store(output, "This is overwrite file");
output
PROPERTIES_KEY_3=OVERWRITE_VALUE
PROPERTIES_KEY_2=PROPERTIES_VALUE_2
PROPERTIES_KEY_1=PROPERTIES_VALUE_1

I would look at Apache Commons Configuration.
It has very specific examples that do what you are asking.
Try:
import org.apache.commons.configuration.PropertiesConfiguration;
PropertiesConfiguration config = new PropertiesConfiguration(
"config.properties");
config.setProperty("my.property", somevalue);
config.save();

Related

How to create new column from CSVWriter in Java

I have a problem. I want to create a new CSV file from CSVWriter and my whole Array is set into the one cell.
This is my java code:
StringWriter s = new StringWriter();
#SuppressWarnings("deprecation")
CSVWriter writer = new CSVWriter(s, '\t');
String[] entries = new String[3];
entries[0] = "Test";
entries[1] = "Test";
writer.writeNext(entries);
writer.close();
String finalString = s.toString();
System.out.println(finalString);
I get the output like this: "first" "second" "third"
and my CSV is :
but I want to be like this:
Your code is OK, the problem is you open the CSV file by Excel with default settings.
If you open the CSV file with Notepad, it will look like this:
"Test" "Test"
And if you still want to open it with Excel, you are supposed to open it by following steps:
Create a new sheet.
Select Data > From Text File.
Select file (write.csv) to be imported.
Click Finish.

Java create a new file, or, override the existing file

What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
You can use a suitable Writer:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.
You can also open the file in append mode by using another constructor of FileWriter:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
The documentation for above constructor says:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.

How to replace the contents of a file after processing

Let's say that I have a TreeMap and I want to take all values for a key, make a file with these, pass the file to another process loop and do this for every map key, so I always have to use the same file but its content must be replaced every time for each key.
What I do is:
PrintWriter writeRatings = new PrintWriter("ratings.txt", "UTF-8");
TreeMap<Integer, ArrayList<Rating>> ratings = new TreeMap<Integer, ArrayList<Rating>>();
-->
for(Integer clID:ratings.keySet()){
ArrayList<Rating> ratingGroup = ratings.get(clID);
for(Rating r:ratingGroup){
witer.println(r.toString());
}
}
writer.flush();
writer.close();
With this, I get a file with all the data for each map key. Can you suggest how can I get only the data from the current key each time in the file?
If you want to use the same file and just append lines to it, use a FileWriter and set the append mode to true
PrintWriter writer = new PrintWriter(new FileWriter("filename", true));
This will append lines to the file, instead of over writing the file. This way, different processes can use the same file and keep on adding new data to the file
So what worked for me was to include this line into the for loop in the position of the arrow in the main question post:
PrintWriter writer = new PrintWriter(new FileWriter("filename"));

Java Properties.store is deleting other entries

I am trying to modify a config file in Java using Properties. I try to modify two of the multiple entries like this:
Properties properties = new Properties();
FileInputStream fin = null;
FileOutputStream fout = null;
fin = new FileInputStream(mCallback.getConfFile());
fout = new FileOutputStream(mCallback.getConfFile());
properties.load(fin);
properties.setProperty(Wrapper.GAME_PATH_KEY, (String)gamePathText.getText());
properties.setProperty(Wrapper.GAME_TYPE_KEY, (String)selectedGame.getSelectedItem());
properties.store(fout, null);
But when I check the file after the result I find out that the whole file was overwritten, leaving only these two entries. This is an android app though I guess it's not relevant to the problem here. What I am doing wrong?
You have to read all properties and then modify the ones you want. After that you have to write all to file. You cannot do only an item modification. The Properties API doesn't provide that functionality to modify.
Edit:
Interchange these two statements-
fout = new FileOutputStream(mCallback.getConfFile());
properties.load(fin);
You should load first before you create a file with the same name.
From Properties:
public void store(OutputStream out,
String comments)
throws IOException
Writes this property list (key and element pairs) in this Properties table to the output > stream in a
format suitable for loading into a Properties table using the
load(InputStream) method.
Properties from the defaults table of this
Properties table (if any) are not written out by this method.
This method outputs the comments, properties keys and values in the
same format as specified in store(Writer), with the following
differences:
So, Load the data first, then set the required data, then store it.
Properties prop =new Properties();
prop.load(new FileInputStream(filename));
prop.setProperty(key, value);
prop.store(new FileOutputStream(filename),null);
The previous poster was kind of right, just not at the right place.
You need to open the FileOutputStream after you've loaded the properties otherwise it clears the file's content.
Properties properties = new Properties();
FileInputStream fin = null;
FileOutputStream fout = null;
fin = new FileInputStream(mCallback.getConfFile());
// if fout was here, the file would be cleared and reading from it would produce no properties
properties.load(fin);
properties.setProperty(Wrapper.GAME_PATH_KEY, (String)gamePathText.getText());
properties.setProperty(Wrapper.GAME_TYPE_KEY, (String)selectedGame.getSelectedItem());
fout = new FileOutputStream(mCallback.getConfFile());
properties.store(fout, null);

Writing to an already existing file using FileWriter Java

Is there anyway I can write to an already existing file using Filewriter
For example when the user clicks a submit button:
FileWriter writer = new FileWriter("myfile.csv");
writer.append("LastName");
writer.append(',');
writer.append("FirstName");
writer.append('/n');
writer.append(LastNameTextField.getText());
writer.append(',');
writer.append(FirstNameTextField.getText());
I want to be able to write new data into the already existing myfile.csv without having to recreate a brand new one every time
Yeah. Use the constructor like this:
FileWriter writer = new FileWriter("myfile.csv",true);
FileWriter
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Categories

Resources