Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the position in a File  RSS feed

 
Kelly Harris
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy.
For example: I want to search a file for a string. If I find the string I would like to replace the text I find with some other text. I was planning on writing the file contents un to that point to a temporary file. Concat the text I want to replace and then concat the rest of the original file.
I cannot seem to find anything that is similar to the seek & tell functions that C/C++ has. Is there anyway to do this other than to write the file out to a temporary location and then about that file is the text is not found?
Thanks
 
Kelly Harris
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I spoke too soon. I will be trying RandomAccessFile. Any other ideas will be appreciated.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
RandomAccessFile will only work here if you're not going to change the length (in bytes) of the string. Plus if you're doing anything performance-critical RAF, well, sucks. As an alternative, it sounds like you don't really need the file position so much as the position within a given String. That is, use BufferedReader's readLine() to get one line at a time from the original file. For each line, use String methods (or in 1.4, the java.util.regex package) to find and replace substrings as desired, and create a new String representing the "new, improved" version of the line (which in some cases may be exactly the same as the old line). Write all these new lines to a temporary file, and when you're done, delete the original and rename the temp to the original file name. Voilà! The file has been transformed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!