This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to replace string in a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to replace string in a file" Watch "How to replace string in a file" New topic

How to replace string in a file

David Sundo

Joined: Nov 13, 2002
Posts: 6
I need help! basically I have a file called "test.txt" The content of the file is as followed:
Honda Civic, 4LSXL,red = 2000
Honda Accord, 3HUV, blue = 1999
Nissan Maxima, 5JKLU, green =2001
Acura Integra, JK22L, red = 2003
Basically I want to replace "Nissan Maxima, 5JKLU, Green=2001" with "Nissan Altima, 6LRTU, Yellow=1999". Can any one tell me what is the easiest way to do this?
I already started to read the file, I need some help!
David Sundo
StringBuffer data = new StringBuffer();

LineNumberReader in = new LineNumberReader(new FileReader("test.txt"));
while ((line = in.readLine()) != null){
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I'll guess you want a Swing UI, and we'll work against the text file kinda like it was a single-user database. See if this sings to you:

Doea that makes sense? Does it hint at some unit tests you can write? Responsibilities for different classes? This is a classic "functional decomposition" analysis, not very OO ... yet.
[ July 21, 2003: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63208

I'll guess you want a Swing UI,

??? I have no idea where Swing or a GUI comes into this...
Basically I want to replace...

Some ideas: you may want to look into regular expressions to locate the text you want to replace (I'm assuming you aren't going to hard-code the string into the program). If you aren't going to do any pattern matching, regular expressions may be over-kill, and you may just need the String.indexOf() method.
Then there are methods in the String class that will help you extract the sub-strings necessary to rebuild a new string using your string buffer.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Yeah, that Swing bit was a leap. If this is the least work you can do to update a file you can start by deciding if you want the whole file in memory or not.

I used to work on an OS called CMS that had a safe file replacement strategy, used in COPY and certain other output that replaced an existing file:

This gives a "least bad" result if anything croaks in mid flight.
Yet another approach: You CAN update the file in place. Force all car records to have the same number of bytes. Use RandomAccessFile to seek a position (record number * record length) and read (record length) bytes. If you find the old data, seek the same position again, and write the new bytes. Just for practice with test first coding, I made a random access fixed length file class with the following public methods:

If that sounds like fun, I'd be happy to share it. Or maybe just the Junit test first.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Stan, I'd enjoy a look at what you did. And if you are in the mood to give us the blow-by-blow through the unit tests and the implementation, well that'd just be... awesome!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I moved this to the IO forum here. So far I just posted the unit tests. Implementation tomorrow?
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Jaunty John

Joined: Jul 14, 2002
Posts: 21
Try this...
//~ Formatted by jFormatïż½2003 EMail: 2003.07.23
import java.util.*;
public class ReadReplaceText {
public static void main(String args[]) throws IOException {
ArrayList inFile = new ArrayList();
ArrayList outFile = new ArrayList();
int iJ=0;
String oldStr = "Nissan Maxima, 5JKLU, Green =2001";//Old_String
String newStr = "Nissan Altima, 6LRTU, Yellow=1999";//New string
try {
FileReader fr = new FileReader("test.txt");// Create a char stream reader
BufferedReader br = new BufferedReader(fr);//A line reader
String str;
while((str = br.readLine()) != null) {
inFile.add(str);//~inFile is an AryFile TYPE
//And now manipulate the file...
for(int iK=0; iK<inFile.size(); iK++) {
str = (String) inFile.get(iK);
iJ = str.indexOf(oldStr);
//iJ will equal 0 when current string matches Old_String
if(iJ == 0) {
outFile.add(iK, newStr);
//System.out.println(">>> " + str);
else {
outFile.add(iK, str);
}//~for(int iK=0; iK<inFile....
//Write the File
PrintWriter pw = new PrintWriter(new FileWriter("test.txt"));
for(int iK=0; iK<inFile.size(); iK++) {
str = (String)outFile.get(iK);
catch (IOException ex) {
}//~public static void main(...
}//~public class ReadReplace...

(((o o)))<br />""--^--"" Entropy is Increasing...
I agree. Here's the link:
subject: How to replace string in a file
It's not a secret anymore!