• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

How to replace string in a file

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I need help! basically I have a file called "test.txt" The content of the file is as followed:
---------------Test.txt---------
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!
Thanks,
David Sundo
------------Code----------------------------
StringBuffer data = new StringBuffer();

LineNumberReader in = new LineNumberReader(new FileReader("test.txt"));
while ((line = in.readLine()) != null){
data.append(line);
data.append("\n");
}
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Sheriff
Posts: 67752
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
hth,
bear
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I moved this to the IO forum here. So far I just posted the unit tests. Implementation tomorrow?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cool.
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try this...
//~ Formatted by jFormat�2003 EMail: [email protected] 2003.07.23
import java.io.*;
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
//System.out.println(str);
}
fr.close();
//And now manipulate the file...
for(int iK=0; iK<inFile.size(); iK++) {
str = (String) inFile.get(iK);
System.out.println(str);
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....
System.out.println();
//Write the File
PrintWriter pw = new PrintWriter(new FileWriter("test.txt"));
for(int iK=0; iK<inFile.size(); iK++) {
str = (String)outFile.get(iK);
pw.println(str);
System.out.println(str);
}
pw.close();
}//~try...
catch (IOException ex) {
ex.printStackTrace();
}
}//~public static void main(...
}//~public class ReadReplace...
 
I didn't like the taste of tongue and it didn't like the taste of me. I will now try this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic