• Post Reply Bookmark Topic Watch Topic
  • New Topic

reading a file, then replacing a string...

 
Rogelio Tristan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
heres the package (compiles great)
http://www.outrun.org/shiz/skool/Students.java



heres the main java file (works and compiles fine)
http://www.outrun.org/shiz/skool/part2.java



Okay, its supposed to create a text.txt file, and it does, then with each student enter in a new entry of student in the text file. which it does fine.

It also can display all the contests of the text file, which is does fine.

however I am extremely stuck at how to get it to search the text file for a certain word, and rplace it with another word. I know I'm going to have to throw the entire text file into an instance of a string, but how (syntactically) would I do that? and how would I make it search and replace the text? I think I have to use the pushback somehow.. right?

any help is appreciated, thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your replacement value is exactly the same length as your find value, you can get real tricky with RandomAccessFile and update it in place. This doesn't often come together unless you have carefully designed fixed length records in your file.

So, much more likely you'll have to read the file, replace the value in memory and rewrite the file. You can read the whole thing into one string and do replacements, or read, replace and write one line at a time. If you're in JDK 1.4 (or want to use a 3rd party jar) you can look at Pattern for regular expressions, otherwise look at String.indexOf() for searching and lots of String.substring() for replacing.

Here's a trick I picked up from an old IBM operating system ...

That's a very paranoid and safe way to avoid losing the file through some error.

Holler if you need guidance on the particulars.
[ November 16, 2004: Message edited by: Stan James ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!