每次“写入”方法使用后清除文件

时间:2013-07-23 16:13:17

标签: java performance

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中较大的问题。

1 个答案:

答案 0 :(得分: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();
}

参考:how to clear contents of a PrintWriter after writing