HELP! How can I search a record in a text file and replace a field in that record?

I'm so new to Java, please help.  I want to search for a record in a text file. Then delete that record or replace a field in that record?  What option I have?  

input file "List.txt" content ...
apple;red;round
apple;green;round
orange;orange;round
banana;yellow;long
orange;orange;big

Wonder19Asked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
to delete it you'll need to create a new file
you can replace an entry but only if you replace it with the same number of characters, otherwise you'll need to create a new file.
0
 
rongasaConnect With a Mentor Commented:
In case the problem is the string parsing think of the above code. StringTokenizer parses the file by using the ";"

StringTokenizer tokenizer = new StringTokenizer(className, ";");
       
        while (tokenizer.hasMoreTokens())
        {
            String token = tokenizer.nextToken();
           
        }

The token could either be String (as above) or StringBuffer. I would suggest StringBuffer due to the functions it has i.e. append.
So you could read each word, apple, green, ... and append only the ones you like to the StringBuffer.

Last with respect to the file as mentioned to the above comment you should better recreate a file. I am not sure whether you would not be able to change the file, i simply do not know that, but i am sure it is the more easy way.
0
 
Giant2Connect With a Mentor Commented:
Here are examples:
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html?l=rel
http://javaalmanac.com/egs/java.io/WriteToFile.html?l=rel
http://javaalmanac.com/egs/java.io/AppendToFile.html?l=rel
http://javaalmanac.com/egs/java.io/UseRandomAccessFile.html?l=rel

1) You can read the full file in memory (a String) and then you can apply your change. After this rewrite the file.
2) You can create a temporary file where you put the file modified (for example: read a line from the original file, apply the changes, save on the newer file). After all modifyes you can rename/copy the new-one on the old-one.

Hope this could help you.
Bye, Giant.
0
 
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.