Parsing a file for a string and then replace it

K

Kevin Kirkeby

I've looked through many of the postings in this forum and the Java
Tutorial, and I have not really been able to find an answer to this
problem. I need to parse a file for a value and replace it with another
value. It would be really slick if there were a class/method that allows
me to do this; however, I have not had any luck finding one. I have
written the following class below that does this. What it does is look
for the the value to be changed and then writes the data (and changed
strings) out to a different file. So, this works but does anyone know if:
1) There is a class/method that does this already?
2) Is it possible to write directly back to the file that I'm parsing?
The code below writes all the output to a new file and then I'll have to
copy it back. (As a result, the authorities are all different from the
original now.)
3) Is there a simpler approach than what I have done below?
4) If below is the only way to do this, would you recommend using
something other than BufferedReader/Writer? Any other suggestions on
making the code better?

Thanks,
Kevin


public class Parser {

public static void replaceString(String str, String newStr)
throws FileNotFoundException, IOException {

FileReader fr = new FileReader("C:\\temp\\my.xml");
FileWriter fw = new FileWriter("C:\\temp\\myNew.xml");
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);

// Look for the string specified by "str"
String line;
int index;
String newLine;
while ((line = br.readLine()) != null) {
if ((index = line.indexOf(str)) != -1) {
// String was found.
newLine = line.substring(0, index)
+ newStr
+ line.substring(index + str.length());
System.out.println("New line: " + newLine);
} else {
newLine = line;
}

bw.write(newLine);
bw.newLine();
}

bw.flush();
bw.close();
}

public static void main(String[] args) {
try {
replaceString("true", "false");
} catch (Exception e) {
System.out.println("Exception in replaceString. " + e.toString());
}
}
}
 
A

Anthony Borla

Kevin Kirkeby said:
I've looked through many of the postings in this forum
and the Java Tutorial, and I have not really been able
to find an answer to this problem. I need to parse a file
for a value and replace it with another value. It would
be really slick if there were a class/method that allows
me to do this; however, I have not had any luck finding
one. I have written the following class below that does this.
What it does is look for the the value to be changed and then
writes the data (and changed strings) out to a different file.
So, this works but does anyone know if:

1) There is a class/method that does this already?

The 'StringTokenizer' class may be used to tokenise / parse a 'String',
while the 'StreamTonenizer' does the same for stream data [also has more
control over the parsing process]. These are both general purpose classes,
and you would need to incorporate them into your own parser class.
2) Is it possible to write directly back to the file that
I'm parsing?

Yes, it is possible: using a 'RandomAccessFile' object allows you can both
read and write to the same file.
The code below writes all the output to a new file and
then I'll have to copy it back. (As a result, the authorities
are all different from the original now.)

You can avoid creating a new file by:

* Using a 'RandomAccessFile' object to write modified data
to the same file - care needs to be taken with this approach
since it is possible to write over data that has not already
been read in [e.g. if replacing a short string with a longer one]
Personally, I wouldn't use this approach, but I'd be remiss if
I didn't mention it

* Read file data into a memory area, make the modifications
in memory, then write out the modified data to the same
file. You could do something like:

- Use 'FileReader' to read all file data into a 'char' array
in one step; close this stream when finished

- Wrap up the 'char' array inside a 'StringBuffer' object
[StringBuffer sb = new StringBuffer(array.length);
sb.append(array);], and make any required
modifications

- Use 'FileWriter' to write the modified 'char' array
data to the same file, all in one step

Alternatively, you could retain the line-by-line processing
approach, and simply append each [modified] line to a
'StringBuffer' instead of writing it out to a stream. Once
all the input has been processed, write the 'StringBuffer'
contents out via a 'FileWriter'

Note that in all cases file timestamp information is updated. if you don't
want this, use a 'File' object to store the original timestamp, and reset
the updated file to this value.
3) Is there a simpler approach than what I have done
below?

I'm not sure about simpler, though certainly there are several different
ways of performing this type of task. Off hand, one thing I'd suggest
changing is to make 'newLine' a 'StringBuffer', and do this:

newLine
.append(line.substring(0, index))
.append(newStr)
.append(line.substring(index + str.length());

instead of concatenating 'String' objects, a much slower process. Of course,
the performance difference may not matter, but it's always nice to know that
your program is as efficient as it could be [without going to extremes :)].
4) If below is the only way to do this, would you recommend
using something other than BufferedReader/Writer ? Any
other suggestions on making the code better?

Use these if you require buffering; if not, don't use them. You can always
perform timing tests with / without them and determine which offers best
performance.

I hope this helps.

Anthony Borla

P.S.

I noticed the extension on your data files was '.xml'. If you need to perfom
any XML parsing / transformation take a look at the 'javax.xml' packages
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top