Reputation: 9915
I am creating a text file using BufferedWriter
BufferedWriter bufferedWriter =
new BufferedWriter(new FileWriter("/home/user/temp.txt"));
/*
Add Contents using bufferedWriter.write()
*/
At certain places while adding contents I add a string sequence ######
Before I do bufferedWriter.close()
I want to replace the ###### sequence with some specific value.
How can I do that?
I do not want to re-open the Writer, but could use a different writer if it allows this to be done.
Upvotes: 2
Views: 4494
Reputation: 38444
I believe you have the following options:
Write your own Writer
. None of the Writers
I know about are able to do this simply because they actually write to disk (into the file) when you call .write()
on them. Some, like BufferedWriter
, don't do it immediatelly, but if you exceed the inner buffer, it will be flushed into the file anyway - even without you calling flush()
or close()
.
Simply use StringBuilder
. Write to a StringBuilder
, then replace your sequence and only then write to a file.
Write to a new file every time you encounter ######
. Effectively, you'll have several files with a missing piece of text in between them. After you know the right sequence that should replace ######
, join the files using that sequence.
If you have enough memory to hold all the data in memory, use a List<String>
(split at the ######
, then join the elements using something like a Joiner
).
Upvotes: 1
Reputation: 320
What about something like that ?
BufferedReader br = new BufferedReader(new FileReader("/home/user/temp.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("/home/user/temp.txt"))
String line
StringBuffer sb = new StringBuffer()
while (line = br.readLine()) {
line = line.replace("######", "yourReplacement")
sb.append(line)
}
br.close()
bw.write(sb.toString(), 0, sb.length())
bw.close()
Upvotes: -1
Reputation: 51553
Create the contents as a String
or a List<String>
.
After you replace the #####
, you write the String
or List<String>
to the BufferedWriter
.
Upvotes: 2