如何在Java中替换大文件的第一行?
我想用 Java 清空文本文件的第一行。该文件有几千兆字节,我不想复制。使用这篇文章的建议,我正在尝试使用 RandomAccessFile 来做到这一点,但是它写得太多了。
这是我的代码:
RandomAccessFile raInputFile = new RandomAccessFile(inputFile, "rw");
origHeaderRow = raInputFile.readLine();
raInputFile.seek(0);
raInputFile.writeChars(Strings.repeat(" ",origHeaderRow.length()));
raInputFile.close();
如果您想要一些示例输入和输出,则会发生以下情况:
之前:
first_name,last_name,age
Doug,Funny,10
Skeeter,Valentine,9
Patti,Mayonnaise,11
Doug,AlsoFunny,10
之后:
alentine,9
Patti,Mayonnaise,11
Doug,AlsoFunny,10
在此示例中,在大多数编辑器中,文件正确地以 24 个空格开头,但 48 个字符(包括换行符)已被替换。粘贴到这里后,我看到了奇怪的问号。双倍大小的替换让我觉得涉及编码的东西变得混乱,但我尝试 writeUTF 得到了相同的结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java中的
char
是2个字节。使用 writeBytes 代替。
来自 JavaDoc< /a> 看起来正是您正在寻找的内容。
char
in Java is 2 bytes.use
writeBytes
instead.From JavaDoc looks exactly what you are looking for.
当您编写字符(在 Java 中为 16 位)时,每个字符使用两个字节。
我建议你尝试写你想要的字节数,否则你的空格将变成
nul
和space
字节。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
andspace
bytes.