This question already has answers here:
Java Properties: How to keep non key=value lines?
(2 answers)
Adding comments in a properties file line by line
(3 answers)
Closed 7 years ago.
I have a .properties file which have number of comments in it, when I try to update the content of the file other than the comments, even though my comments are disappearing, how to retain my comments?
Here is the config.properties file:
#name of user
name=user1
#id of user
id=id1
and the code to update the properties file, I used
public class SetLog {
public static void setPath()
{
File file = new File("./config.properties");
Properties prop = new Properties();
FileInputStream objInput = null;
try {
objInput = new FileInputStream(file);
prop.load(objInput);
objInput.close();
FileOutputStream out = new FileOutputStream("./config.properties");
//update the content
prop.setProperty("name", "user2");
prop.store(out, null);
out.close();
} catch (Exception e) {}
}
}
After I run the above code, properties file content changed to:
name=user2
id=id1
But I want in this format:
#name of user
name=user2
#id of user
id=id1
How to retain my comments, please help!
This has been answered in a similar question: Adding comments in a Property File. Basically it boils down to using the Apache Commons extension to read and write Property Files.
Try to read the characters in the file and ignore those lines beginning with # .
See this link
Related
This question already has answers here:
How do I load a resource and use its contents as a string in Spring
(7 answers)
Closed 9 months ago.
I have a text file with path as resources/templates/temp.txt. I tried reading it with built in Files.readAllBytes() function found in java.nio but that results in an NullPointerException. My code looks as follows:
try {
File file = new File(getClass().getResource("templates/temp.txt").getFile());
String temp = new String(Files.readAllBytes(Paths.get(file.getPath())));
System.out.println(temp);
}catch(Exception e){
e.printStackTrace();
}
The file actually does exist at this location because I am able to get an InputStream and use that in an InputStreamReader and BufferedReader to read the file line-by-line.
InputStream input = this.getClass().getClassLoader().getResourceAsStream(path)
//path here is "templates/temp.txt"
I would like to read this file with a built in method rather than iterating over the entire thing.
Would appreciate it very much if someone can help with this. Thanks in advance!
How does your code even compile? You have static reference in non-static env:
... new File(getClass().getResource ...
try to get the bytearray before transforming into string:
try {
byte[] tmpba = Files.readAllBytes(Paths.get("templates/temp.txt"));
String s = new String(tmpba);
System.out.println(s);
}catch(Exception e){
e.printStackTrace();
}
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 4 years ago.
I open file as follows
private static Formatter x;
public static void openFile(){
try{
x=new Formatter("sarit.text");
}
catch(Exception e){
System.out.println("error");
}
}
Here I add a information to the file but the problem of adding the information to this file erases everything that was in the file before inserting the information
public static void addRecords(String age,String city,String name, String password){
x.format(" "+name+" "+password+" "+age+" "+city+"\n");
}
public static void closeFile(){
x.close();
}
Welcome to StackOverflow!
You are doing new Formatter("sarit.text");
Checking javadoc for
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)
if the file exists then it will be truncated to zero size
you need to append to file.
Question How to append text to an existing file in Java provides answers how to append to file in java.
Assuming you're using java.util.Formatter, the documentation specifically says:
If the file exists then it will be truncated to zero size; otherwise,
a new file will be created
You have to find a different way to do it, with a BufferedWriter for example:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
The true parameter tells the FileWriter to append to the file.
If you want to use formatting, use String.format():
writer.write(String.format(...));
Content of data.txt file
pin=9876
balance=9001
investment=10000
interest=0.065
isLockedOut=false
My code currently:
import java.io.*;
import java.util.Properties;
public class SetData extends ATM {
public static void setIsLockedOut(boolean isLockedOut) { //Sets the isLockedOut variable
try {
Properties data = new Properties();
FileOutputStream output = new FileOutputStream("data.txt");
if (isLockedOut = true) {
data.setProperty("isLockedOut", "true");
data.store(output, null);
output.close(); //Closes the output stream
}
else {
data.setProperty("isLockedOut", "false");
data.store(output, null);
output.close();
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I have also checked and referred to a similar question on StackOverflow as well (Updating property value in properties file without deleting other values).
The method 'setIsLockedOut' is called from another class.
When I call this method to set the 'isLockedOut' variable to true in the 'data.txt' file, all other variables are erased except the 'isLockedOut' variable. This is the output:
#Sun Nov 17 15:44:42 EST 2013
isLockedOut=true
So my question is, how can I update a property value without erasing the other values in the file?
All you are doing is overwriting the data.txt file with the content of data which is just the value of "isLockedOut". It seems that what you want to do is to overwrite data.txt with all of the properties that used to be in data.txt, plus an updated value for "isLockedOut". To do that, you need to open data.txt for reading and read its content into data, then modify data, then overwrite data.txt with the new data. Skipping the first step is what is causing your problem.
You need to use a FileInputStream and the load method. Use them much the same way you are using FileOutputStream and store already.
I've different properties file as shown below:
abc_en.properties
abc_ch.properties
abc_de.properties
All of these contain HTML tags & some static contents along with some image urls.
I want to send email message using apache commons email & I'm able to compose the name of the template through Java using locale as well.
String name = abc_ch.properties;
Now, how do I read it to send it as a Html Msg parameter using Java?
HtmlEmail e = new HtmlEmail();
e.setHostName("my.mail.com");
...
e.setHtmlMsg(msg);
How do I get the msg param to get the contents from the file? Any efficient & nice solun?
Can any one provide sample java code?
Note: The properties file has dynamic entries for username & some other fields like Dear ,....How do I substitute those dynamically?
Thanks
I would assume that *.properties is a text file.
If so, then do a File read into a String
eg:
String name = getContents(new java.io.File("/path/file.properties");
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
InputStreamReader fr=new InputStreamReader(new FileInputStream(aFile), "UTF8");
input = new BufferedReader( fr );
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
//ex.printStackTrace();
}
catch (IOException ex){
//ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
//ex.printStackTrace();
}
}
return contents.toString();
}
regards
Hi Mike,
Well, I kind of guess that you are trying to send mails in multiple languages by rendering the elements from different property files at runtime. Also, you said "locale". Are you using the concept of "Resource Bundles )"? Well, in that case before you send mails,
1)You need to understand the naming conventions for naming a property file, without which the java compiler will not be able to load the appropriate property file at run time.
For this read the first page on the Resource Bundles page.
2) Once your naming conventions is fine, you can load the appropriate prop file like this:
Locale yourLocale = new Locale("en", "US");
ResourceBundle rb = ResourceBundle.getBundle("resourceBundleFileName", yourLocale);
3) Resource Bundle property file is nothing but a (Key,Value) pairs. Hence you can retrieve the value of a key like this:
String dearString = rb.getString("Dear");
String emailBody= rb.getString("emailBody");
4) You can later use this values for setting the attributes in your commons-email api.
Hope you find this useful!
I need to write something into a text file's beginning. I have a text file with content and i want write something before this content. Say i have;
Good afternoon sir,how are you today?
I'm fine,how are you?
Thanks for asking,I'm great
After modifying,I want it to be like this:
Page 1-Scene 59
25.05.2011
Good afternoon sir,how are you today?
I'm fine,how are you?
Thanks for asking,I'm great
Just made up the content :) How can i modify a text file like this way?
You can't really modify it that way - file systems don't generally let you insert data in arbitrary locations - but you can:
Create a new file
Write the prefix to it
Copy the data from the old file to the new file
Move the old file to a backup location
Move the new file to the old file's location
Optionally delete the old backup file
Just in case it will be useful for someone here is full source code of method to prepend lines to a file using Apache Commons IO library. The code does not read whole file into memory, so will work on files of any size.
public static void prependPrefix(File input, String prefix) throws IOException {
LineIterator li = FileUtils.lineIterator(input);
File tempFile = File.createTempFile("prependPrefix", ".tmp");
BufferedWriter w = new BufferedWriter(new FileWriter(tempFile));
try {
w.write(prefix);
while (li.hasNext()) {
w.write(li.next());
w.write("\n");
}
} finally {
IOUtils.closeQuietly(w);
LineIterator.closeQuietly(li);
}
FileUtils.deleteQuietly(input);
FileUtils.moveFile(tempFile, input);
}
I think what you want is random access. Check out the related java tutorial. However, I don't believe you can just insert data at an arbitrary point in the file; If I recall correctly, you'd only overwrite the data. If you wanted to insert, you'd have to have your code
copy a block,
overwrite with your new stuff,
copy the next block,
overwrite with the previously copied block,
return to 3 until no more blocks
As #atk suggested, java.nio.channels.SeekableByteChannel is a good interface. But it is available from 1.7 only.
Update : If you have no issue using FileUtils then use
String fileString = FileUtils.readFileToString(file);
This isn't a direct answer to the question, but often files are accessed via InputStreams. If this is your use case, then you can chain input streams via SequenceInputStream to achieve the same result. E.g.
InputStream inputStream = new SequenceInputStream(new ByteArrayInputStream("my line\n".getBytes()), new FileInputStream(new File("myfile.txt")));
I will leave it here just in case anyone need
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (FileInputStream fileInputStream1 = new FileInputStream(fileName1);
FileInputStream fileInputStream2 = new FileInputStream(fileName2)) {
while (fileInputStream2.available() > 0) {
byteArrayOutputStream.write(fileInputStream2.read());
}
while (fileInputStream1.available() > 0) {
byteArrayOutputStream.write(fileInputStream1.read());
}
}
try (FileOutputStream fileOutputStream = new FileOutputStream(fileName1)) {
byteArrayOutputStream.writeTo(fileOutputStream);
}