Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Aaron Silverman Avatar asked Aug 19 '11 20:08

Aaron Silverman


People also ask

How do I change the first line of a text file in Java?

First use BufferedReader 's readLine() to read the first line. Modify it and write it to the BufferedWriter . Then use a char[] array to perform a brute-force copy of the remainder of the file.

How do you replace a specific line in a file using Java?

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters. Instantiate the FileWriter class. Add the results of the replaceAll() method the FileWriter object using the append() method.

How do I remove the first line from a text file in Java?

Scanner fileScanner = new Scanner(myFile); fileScanner. nextLine(); This will return the first line of text from the file and discard it because you don't store it anywhere.

How do you add a line at the beginning of a file in Java?

Append a single line to a file – Files.write(path, content. getBytes(StandardCharsets. UTF_8), StandardOpenOption. APPEND);


1 Answers

char in Java is 2 bytes.

use writeBytes instead.

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

From JavaDoc looks exactly what you are looking for.

like image 137
Alexander Pogrebnyak Avatar answered Oct 19 '22 11:10

Alexander Pogrebnyak