简体   繁体   English

如何在JAVA中使用PrintWriter从顶部写回?

[英]How to write back from top using PrintWriter in JAVA?

Using PrintWriter to write to a txt file. 使用PrintWriter写入txt文件。 But now I have a problem: Can I write from the top line after I write some lines? 但是现在我有一个问题:写完几行后可以从第一行开始写吗? For example, I have write: 例如,我写了:

PrintWriter out = new PrintWriter("result.txt");
out.print("first line");
out.print("second line");

Then, can I write back from the first line? 然后,我可以从第一行写回吗? So I can write the String top = "top line" before the first line like the following: 因此,可以在第一行之前编写String top =“ top line”,如下所示:

top line
first line
second line

The problem is, I can get the content of String top only after I write "top line" and "second line". 问题是,只有在编写“ top line”和“ second line”之后才能获取String top的内容。 How can I write to the beginning of the file? 如何写入文件的开头?

Thank you! 谢谢!

A simple way to implement this, would simply be to read in the entire file as a string, append your pre-fix line onto the start of it, and overwrite the contents of the file with the String's content using a PrintWriter object. 一种简单的实现方法是,将整个文件作为字符串读取,将前缀行附加到文件的开头,然后使用PrintWriter对象用String的内容覆盖文件的内容。 It's not exactly what you wanted, but it has the exact same effect. 它不是您想要的,但是效果完全相同。 :) :)

Use RandomAccessFile class and its seek method, but write on top doesn't insert lines but overwrites them. 使用RandomAccessFile类及其seek方法,但在最上面写不会插入行,但会覆盖它们。 It's not that you want. 不是你想要的。 I agree with JB Nizet comment, the best is to compute first, then write. 我同意JB Nizet的评论,最好是先计算,然后编写。

If you known the size of the first line you have to write 'XXXXXXXXXXXXXXX' to fill it and after writing the others lines, back to the top and replace it by the good one with the same count of characters. 如果您知道第一行的大小,则必须写'XXXXXXXXXXXXXXX'来填充它,并在写完其他行之后,回到顶部,并用字符数相同的好行替换它。 Possible but not recommended. 可能但不建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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