how to write in properties file without deleting old values - java

I want to write in properties file without removing earlier written values in file.
for Eg there is value in properties file
token = tokengenerated
Now when I again set new value like
token1 = tokensnew
Then the properties file should show
token = tokengenerated
token1 = tokensnew

Pass true as a second argument to FileWriter to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference

You should read file and update it through properties and streams.
below is the code snippet is help you.
public class ReadAndWriteProperties {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String propertiesFileName = "config.properties";
File f = new File(propertiesFileName);
InputStream input = new FileInputStream(f);
if (input != null) {
props.load(input);
props.setProperty("token2", "tokensnew");
OutputStream out = new FileOutputStream(f);
props.store(out, "save");
}
}
}

You must read the file (var1), then add your content to the var1 and then write the var1 to the file.

Related

Saving properties into a file are interpreted by store method

I have a properties file 1, which after ordering it and eliminating duplicates, I save it in a new properties file 2. My problem is that when saving my properties, the store method is interpreting the text of my property and saves it interpreted, not as it is.
This is my method:
void saveProperties(Properties properties) {
File file = new File("C:\\Files\\new.properties");
FileOutputStream fileOutputStream = new FileOutputStream(file);
properties.store(fileOutputStream, "Properties");
}
This is my store method Override, so it doesn't add escape characters:
public void store(OutputStream out, Properties properties) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
bw.write("#" + new Date().toString());
bw.newLine();
synchronized (this) {
for (Enumeration e = properties.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String val = (String) properties.get(key);
// Commented out to stop '/' or ':' or '#' chars being replaced
// key = saveConvert(key, true, escUnicode);
// val = saveConvert(val, false, escUnicode);
bw.write(key + "=" + val);
bw.newLine();
}
}
bw.flush();
}
These are my two test properties.:
myPropertieTest1=Sure?\\nplease click \\'here\\' to see more info.
myPropertieTest2=Requirements\:<br/>\n" + "name, surname, address.
And this is the result saved in my new properties file:
mypropertietest1=Sure?\nplease click \'here\' to see more info.
mypropertietest2=Requirements:<br/>
" + "name, surname, address.
The escape characters disappear, even in Test2 the property is saved in two lines because the line breaks are interpreted.
I am not sure how you are loading the properties value, but when I tried it on local it works without this issue:
public class Demo{
public static void main(String[] args) throws IOException {
Demo demo = new Demo();
FileReader reader = new FileReader("old.properties");
Properties prop = new Properties();
prop.load(reader);
demo.saveProperties(prop);
}
void saveProperties(Properties properties) throws IOException {
File file = new File("new.properties");
FileOutputStream fileOutputStream = new FileOutputStream(file);
properties.store(fileOutputStream, "Properties");
}
}

Possible to copy specific characters of a file based on a predefined condition?

Possible to copy specific characters of a file based on a predefined condition?
I have a method which copies a file, I need to add more functionality to this method so that characters before the = will solely be copied.
Current Config File:
runInTFS=true
browser=chrome
My method will copy the file above to a new file (.properties) but nothing more:
public static void copyConfigFileForTFS(String configPropertiesDirectory, String tfsConfigPropertiesDirectory) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader(configPropertiesDirectory);
out = new FileWriter(tfsConfigPropertiesDirectory);
int c;
while ((c = in.read()) != -1) {
char singleChararcter = (char) c;
out.write(singleChararcter);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
The method above will add a | after each character (For Testing purposes) i need a way to read :
Existing file (File which i will copy):
runInTFS=true
browser=chrome
url=example.com
New output File should look like (All characters after = need to be removed):
runInTFS
browser
url
I have the following method which will read and output the characters from the old file to the new file, I can append characters to singleChararcter and in turn will reflect the new file but how do I only read and write characters before the = on each line?
Because you are reading a properties files and you are looking just for the keys, you can also load the file content into an instance of a java.util.Properties and then loop over the keys.
Properties prop = new Properties();
InputStream input = new FileInputStream(youtInputFile);
prop.load(input); // load the properties file
OutputStreamos = new FileOutputStream("yourOutPutFile");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
for(Object key: prop.keySet()) { // loop over the property keys
bw.write(key.toString());
bw.newLine();
}
This can give you the possibility to use Properties like browser=chrome=aaa=bbb=ccc=ddd without been concerned by the number of the position of the = sign

FileWriter and PrintWriter won't output to file

I have this code
public User createnewproflie() throws IOException
{
FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
String filename= "users.txt";
Scanner userFile = new Scanner(filename); //creates new obj that reads from file
User usr=new User(); //creates new user istance
String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname
userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0"); //writes usrname in file
userfile.flush();
usr.setName(usrname); //gives usr the selected usname
return usr;
}
and it doesn't output on the file... can someone help please?
i knew that flush would output all of the buffered text but it doesn't seem to work for some strange reason...
You can use a String with a FileWriter but a Scanner(String) produces values scanned from the specified string (not from a File). Pass a File to the Scanner constructor (and it's a good idea to pass the same File to your FileWriter). And you need to close() it before you can read it; maybe with a try-with-resources
File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
PrintWriter userfile = new PrintWriter(fwriter);) {
// ... Write stuff to userfile
} catch (Exception e) {
e.printStackTrace();
}
Scanner userFile = new Scanner(f);
Finally, I usually prefer something like File f = new File(System.getProperty("user.home"), "users.txt"); so that the file is saved in the user home directory.

Java deletes my file and creates a new one

I am trying to finish a bank accounts homework assignment. I have a text file, "BankAccounts.txt" which is created if there is no file with that name. However, if the file exists, I do not create it. But Java desides to delete all my code inside of it :(. Can you help me identify why this happens? Thanks <3
Code:
static Scanner keyboard = new Scanner(System.in);
static File file;
static PrintWriter Vonnegut; //a great writer
static FileReader Max;
static BufferedReader Maxwell;
public static void main(String[] args) {
initialize();
}
static void initialize(){
try { // creating banking file
file = new File("src/BankAccounts.txt");
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
Max = new FileReader("src/BankAccounts.txt");
Maxwell = new BufferedReader(Max);
//get list of usernames and passwords for later
usernames = new String[countLines() / 5];
passwords = new String[usernames.length];
checkingAccounts = new String[usernames.length];
savingsAccounts = new String[usernames.length];
} catch (IOException e) {
e.printStackTrace();
}
}
And this method keeps returning 0... regardless of whether or not my file has data in it.
static int countLines() throws IOException {
BufferedReader Kerouac = new BufferedReader(Max);
int lines = 0;
while(Kerouac.readLine() != null)
lines++;
Kerouac.close();
System.out.println(lines);
return lines;
}
After I run the program, unless I call a method that writes to the file, all the contents of the file will be gone.
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Redundant. Remove.
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
This always creates a new file, which is why the previous line is redundant. If you want to append to the file when it already exists:
Vonnegut = new PrintWriter(new FileOutputStream("src/BankAccounts.txt", true),"UTF-8");
The true parameter tells the FileOutputStream to append to the file.
See the Javadoc.
Or use a FileWriter instead of a FileOutputStream, same principle.
When you create a PrintWriter it will always delete the file if it already exists, from the javadoc:
... If the file exists then it will be truncated to zero size ...
(i. e. its content will be deleted)
Instead of using FileReader and PrintWriter you need to use a RandomAccessFile to write and/or read your file in this way:
RandomAccessFile myFile = new RandomAccessFile("/path/to/my/file", "rw");
In this way the file is automatically created if it doesn't exist, and if it does, it just opens it.

Reading filepath from properties file

I'm trying to read a file from a filepath read from properties, but I keep getting FileNotFoundException (the file exists).
test.properties:
test.value = "src/main/resources/File.csv"
LoadProperties.java:
public class LoadProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties aProp = new Properties();
aProp.load(new FileInputStream("src/main/resources/test.properties")); // works
String filepath = aProp.getProperty("test.value");
System.out.println(filepath); // outputs: "src/main/resources/File.csv"
FileReader aReader = new FileReader("src/main/resources/File.csv"); // works
FileReader aReader2 = new FileReader(filepath); // java.io.FileNotFoundException
}
}
Why is this exception being thrown while the line above it works just fine?
How should I read a file from a path provided with properties?
You are not supposed to put " in your property file. Here Java sees it as :
String file = "\"src/main/resources/File.csv\"";
test.value =src/main/resources/File.csv
You don't need double quotes in properties file to represent a continuous string.
you can write own logic to read properties file, it does not matter whether single quotes or double quotes are there in the file path
String propertyFileLocation = "C:\a\b\c\abc.properties";
try
{
fileInputStream = new FileInputStream(propertyFileLocation);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
properties = new Properties();
String currentLine = null;
String[] keyValueArray = null;
while ((currentLine = bufferedReader.readLine()) != null) {
if (!currentLine.trim().startsWith("#")) {
keyValueArray = currentLine.split("=");
if (keyValueArray.length > 1) {
properties.put(keyValueArray[0].trim(), keyValueArray[1].trim().replace("\\\\","\\"));
}
}
}
}
catch (Exception e)
{
return null;
}

Categories

Resources