2013-07-23 23 views
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(...)都附加到文件中,以便輸出包含一百條消息,而只有最後一個是需要的。什麼是最好的(我的意思是最優雅或有效的)方法來做我想做的事情?在每次「寫入」方法使用後清除文件

UPDATE

答案如「只是打印的最後一個值」是不可接受的,因爲本例中爲從大問題只SSCCE。

回答

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

相關問題