Code to Modify the contents of a file.

Hi,

The contents of the .log file are as mentioned below,

12/02/2005,12:30:06:09,12/02/2005,12:40:09:09,failure,ind-mhp1dxp0323

In this I want to change the status from say "failure" to "sucess" for a particular line.

I want the solution to do this using File Io , Random Access file.

[316 byte] By [moni123a] at [2007-10-1 3:20:01]
# 1
Good idea.Do you have a question?
Peter-Lawreya at 2007-7-8 21:58:49 > top of Java-index,Administration Tools,Sun Connection...
# 2

It is worth noting that random access is only any good if you know exact where you need to be reading/writing. If you have a text file e.g. a log, you don't know this so random access may not be appropriate.

Additional random access does not allow you to insert or delete within a file. i.e. what you write must be the same size as what you replace.

Peter-Lawreya at 2007-7-8 21:58:49 > top of Java-index,Administration Tools,Sun Connection...
# 3
But what is the solution how this can be achieved? Can u give the code for the same?
moni123a at 2007-7-8 21:58:49 > top of Java-index,Administration Tools,Sun Connection...
# 4

> Good idea.

> Do you have a question?

Clearly, this is a "how to" question.

Moni, you're going to have to become familiar with the java.io package, especially the File, FileReader, and FileWriter classes. You may also find the CharBuffer class useful.

Basically, a File represents the location on the computer of a File. A FileReader reads the contents of a file as chars. (Actually, the FileReader.read() method returns an int, but if you cast it to a char, it's the correct char.) A FileWriter writes to a File, and a CharBuffer holds a bunch of chars.

1) First, you have to create the File.

2) Then you need to create a FileReader.

3) Then create a CharBuffer.

4) Use FileReader.read(CharBuffer) and it will put all the chars into the CharBuffer for you.

5) Use CharBuffer.toString() to get a String of the contents of the File.

6) Use one of String's replacement methods.

7) Create a FileWriter that overwrites the contents.

8) Use the FileWriter to write the String that you get after replacing into the File.

9) Close the FileReader and FileWriter.

That's probably the least complicated way, but I'm sure there's a way you can replace just the part you want to and not the whole file. I don't know what it is, though.

Legend_Keepera at 2007-7-8 21:58:49 > top of Java-index,Administration Tools,Sun Connection...
# 5

> > Good idea.

> > Do you have a question?

>

> Clearly, this is a "how to" question.

>

reads more like a "do my homework for me" question.

See how he writes "I want the solution using XXXXX" which signifies he has been told to use a specific API which doesn't typically happen when people just want pointers towards a solution :)

jwentinga at 2007-7-8 21:58:49 > top of Java-index,Administration Tools,Sun Connection...