2017-07-03 90 views
0

在打印語句的集合中,如何只打印一次特定的語句?只打印一次特定的打印語句

例子:

public static void nameHere (arguments) 
{ 
       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
       Date date = new Date(); 
       FileWriter fw = new FileWriter(filepath,true); 
       BufferedWriter bw = new BufferedWriter(fw); 
       PrintWriter pw = new PrintWriter(bw); 
       pw.println("A , B, C, D, E, F, G, "); //I want to print this satement only once 
       pw.print(dateFormat.format(date)); 


        if (condition 1) 
        { 
         pw.println("Print STmt1"); 
        } 
        else if (condition 2) 
        { 
         pw.println("Print STmt1"); 

        } 
        else if (Condition 3) 
        { 
         pw.println("Print STmt1"); 

        } 
        else 
        { 
         pw.println("Print STmt1"); 
        } 

       pw.flush(); 
       pw.close(); 
} 

這實際上日誌附加在 「文件路徑」 中提到的CSV文件,我只想打印行 「pw.println(」 A,B,C,d,E ,F,G「);」儘管我多次調用該程序,但只有一次。

有沒有一種方法可以做到這一點?

+0

跟蹤您是否已打印的語句(如用布爾),以及前檢查布爾的值檢查再次打印。 –

+0

不要在'FileWriter'的構造函數中傳遞'true'。它會在調用程序時多次覆蓋內容。 –

+0

你執行該程序多次或方法?如果它的整個程序使用.properties文件,該文件包含一個值,您可以根據該值確定是否已經打印語句 – XtremeBaumer

回答

1
private static boolean wasPrinted = false; 

public static void nameHere(arguments) { 
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    Date date = new Date(); 
    FileWriter fw = new FileWriter(filepath, true); 
    BufferedWriter bw = new BufferedWriter(fw); 
    PrintWriter pw = new PrintWriter(bw); 
    if (!wasPrinted) { 
     pw.println("A , B, C, D, E, F, G, "); 
     wasPrinted = true; 
    } 
    pw.print(dateFormat.format(date)); 

    if (cond 1) { 
     pw.println("Print STmt1"); 
    } else if (cond 2) { 
     pw.println("Print STmt1"); 

    } else if (cond 3) { 
     pw.println("Print STmt1"); 

    } else { 
     pw.println("Print STmt1"); 
    } 

    pw.flush(); 
    pw.close(); 
} 

編輯你的代碼,你發佈,並添加你需要做的

+0

但這執行代碼的語句 「pw.println(」 A,B,C,d,E,F,G, 「);」如果我初始化wasPrinted爲false,則每次和每次都調用nameHere()方法。如果我將它初始化爲true,它根本不打印該語句。 –

+0

「我剛要打印的行‘pw.println(’A,B,C,d,E,F,G,‘);’雖然我調用該程序多次只許一次」即標誌位不會程序之間仍然存在調用。 –

+0

@tobias_k他在一些註釋所聲明,他只是執行公式的幾個次,但不是全部的program – XtremeBaumer

1

您可以創建一個簡單的標誌文件。

如果此文件不存在,則表示print語句未執行。打印它並創建一個文件。

如果此文件存在,則表示print語句被執行。不要打印任何東西。

File file = new File("flag.txt"); 
if(!file.exists()) { 
    pw.println("A , B, C, D, E, F, G, "); //I want to print this satement only once 
    file.createNewFile(); 
} 
+0

@XtremeBaumer如何檢查w.r.t PrintWriter,FileWriter? –

+0

@RamanSahasi作爲運算現在澄清,他只是執行方法幾次,所以你以前的解決方案是好的 – XtremeBaumer

+0

好主意,但不是一個單獨的標誌文件,爲什麼不利用文件寫入到自身?它不存在,創建它並寫入標題,然後(以其他方式)寫入新行。 –