简体   繁体   中英

How can I replace the first line of a large file in Java?

I would like to blank out the first line of a text file in Java. This file is several gigabytes and I do not want to do a copy. Using the suggestion from this post , I am attempting to do so using RandomAccessFile, however it is writing too much.

Here is my code:

RandomAccessFile raInputFile = new RandomAccessFile(inputFile, "rw");
origHeaderRow = raInputFile.readLine();
raInputFile.seek(0);
raInputFile.writeChars(Strings.repeat(" ",origHeaderRow.length()));
raInputFile.close();

And if you want some sample input and output, here is what happens:

Before:

first_name,last_name,age
Doug,Funny,10
Skeeter,Valentine,9
Patti,Mayonnaise,11
Doug,AlsoFunny,10

After:

                        alentine,9
Patti,Mayonnaise,11
Doug,AlsoFunny,10

In this example, in most editors the file correctly begins with 24 blank spaces, but 48 characters (including newlines) have been replaced. After pasting into here I see strange question mark things. The double size replacement makes me thing something involving encoding is getting messed up but I tried writeUTF with the same results.

char in Java is 2 bytes.

use writeBytes instead.

raInputFile.writeBytes(Strings.repeat(" ",origHeaderRow.length()));

From JavaDoc looks exactly what you are looking for.

As you are writing chars (which in Java are 16-bit) each character uses two bytes. I suggest you try writing the number of bytes you wants otherwise your spaces will turn into nul and space bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM