0
import java.io.*;

public class Main {

    public static void main(String[] args) 
    {
        PrintWriter pw = null;
        //case 1:
        try
        {   
            pw = new PrintWriter(new BufferedWriter(new FileWriter(new File("case1.txt"),false)),true);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        for(int i=0;i<100;i++)
            pw.write("Hello " + String.valueOf(i));

        pw.close();

        //case 2:
        try
        {
            pw = new PrintWriter(new FileWriter(new File("case2.txt"),false),true);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        for(int i=0;i<100;i++)
            pw.write("Hello " + String.valueOf(i));

        pw.close();
    }
}

在这两种情况下,pw.write(...)附加到文件,以便输出包含一百条消息,而只需要最后一条。做我想做的最好的(我的意思是最优雅或最有效的)方法是什么?

更新

像“只打印最后一个值”这样的答案是不可接受的,因为这个例子只是来自更大问题的 SSCCE。

4

1 回答 1

0

我不清楚这种方法的哪些部分可以控制,哪些部分不能控制。很明显,如果您可以控制 for 循环,这将很容易。但是,从您的示例看来,您可以控制的是 PrintWriter 的创建。如果是这种情况,与其直接从 FileWriter 创建它,不如从内存中的流中创建它,然后您可以随意处理内存中的流。

使用 StringWriter 创建内存中的 PrintWriter。您可以从 StringWriter 获取底层缓冲区,并在需要时将其清除。

StringWriter sr = new StringWriter();
PrintWriter w = new PrintWriter(sr);

// This is where you pass w into your process that does the actual printing of all the lines that you apparently can't control.
w.print("Some stuff");
// Flush writer to ensure that it's not buffering anything
w.flush();

// if you have access to the buffer during writing, you can reset the buffer like this:
sr.getBuffer().setLength(0);

w.print("New stuff");

// write to final output
w.flush();



// If you had access and were clearing the buffer you can just do this.
String result = sr.toString();

// If you didn't have access to the printWriter while writing the content
String[] lines = String.split("[\\r?\\n]+");
String result = lines[lines.length-1];

try
{
    // This part writes only the content you want to the actual output file.
    pw = new PrintWriter(new FileWriter(new File("case2.txt"),false),true);
    pw.Print(result);
}
catch(IOException e)
{
    e.printStackTrace();
}

参考:如何在写入后清除 PrintWriter 的内容

于 2013-07-23T17:16:13.643 回答