LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [Java] How to append something to each line in a text file ? (https://www.linuxquestions.org/questions/programming-9/%5Bjava%5D-how-to-append-something-to-each-line-in-a-text-file-719325/)

Kunsheng 04-15-2009 11:53 AM

[Java] How to append something to each line in a text file ?
 
Hello everyone,

I am thinking of appending something to each line in a text file with Java. I prefer not write a new file with content appended from the old one.

That 'something' would probably be Time Stamp when the file is created (which is same for each line).

I am not sure Java provide some easy way for it or not.

Appreciate any idea from you guys,


Thanks in advance,

-Kun

Robhogg 04-15-2009 12:19 PM

I don't think the standard Java library provides anything ready-built to do this (though I did a quick search and it looks like a few people have had a go at implementing sed in Java). In fact, sed -i does create a new temporary file, outputs the modifications to it, then overwrites the original. You can see this if you attempt to use it in a folder in which you do not have write permissions:

Code:

rob:secdir$ sed -i "s/$/ $date/" file
sed: couldn't open temporary file ./sedXlilKP: Permission denied

... In other words,
Code:

sed -i "s/$/ $date/" file
is equivalent to:
Code:

sed "s/$/ $date/" file > tmp_file && mv tmp_file file
You could, of course, read the contents of the file into an ArrayList, append the timestamp to each element of this, and then truncate the file and write the data back again (so long as it was not too large to hold efficiently in memory).

Kunsheng 04-15-2009 02:38 PM

Thanks, Rob! I think I will take this instead of Javaing.


Quote:

Originally Posted by Robhogg (Post 3509906)
I don't think the standard Java library provides anything ready-built to do this (though I did a quick search and it looks like a few people have had a go at implementing sed in Java). In fact, sed -i does create a new temporary file, outputs the modifications to it, then overwrites the original. You can see this if you attempt to use it in a folder in which you do not have write permissions:

Code:

rob:secdir$ sed -i "s/$/ $date/" file
sed: couldn't open temporary file ./sedXlilKP: Permission denied

... In other words,
Code:

sed -i "s/$/ $date/" file
is equivalent to:
Code:

sed "s/$/ $date/" file > tmp_file && mv tmp_file file
You could, of course, read the contents of the file into an ArrayList, append the timestamp to each element of this, and then truncate the file and write the data back again (so long as it was not too large to hold efficiently in memory).


jay73 04-15-2009 09:08 PM

Well, most if not all of that can be done if you learn java regular expressions.


All times are GMT -5. The time now is 05:42 PM.