File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Reading and Writing using a Large Random Access File Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Reading and Writing using a Large Random Access File" Watch "Reading and Writing using a Large Random Access File" New topic
Author

Reading and Writing using a Large Random Access File

Michael Cuoco
Greenhorn

Joined: Jun 12, 2009
Posts: 4
I have a delimited file where each line is of a varying length and can have a varying amount of delimiters. I need to access a random line and replace it with a new line that may be shorter or longer in length. Because the file is large (20MB+), I need to do this as efficiently as possible.

I started with trying to write a simple program that would take a line number, a string, and a file, move to the designated line number, and replace the existing line with the new string. I wanted to scan through the file and after n number of end line characters were reached, write the string after that position.

For example, the program below is supposed to take a file like this:


and change it to this:


The output of my program is below. As you can see, I can't even seem to get a char to read properly. What am I doing wrong?
Path=F:\Eclipse\Workspace\FlashCards\test.txt
Char at 0=?
Char at 2=?
.
.
.
Char at 28=?
Char at 30=?
Reached EOF!
Line 1 File Position=0
Done

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

When you call readChar(), your program is actually reading two bytes - since a char is two bytes in size. readChar() should only be used when the value has been written using writeChar().

RandomAccessFile is not a good class for this problem. It cannot add to a file or remove from a file - it can only replace bytes with an equal amount of bytes. That's not what you specified. Check out FileReader and FileWriter instead. You can't read from and write to the same file at the same time though, so you have to either a) read everything first, or b) write to a new file first, then delete the original and rename the new file.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Michael Cuoco
Greenhorn

Joined: Jun 12, 2009
Posts: 4
After doing some more research on Random Access Files I just scrapped that idea. I ended up doing what you suggested instead and just reading the whole file in, working with it in memory, and saving it at the end.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading and Writing using a Large Random Access File