仅打印一次特定的打印语句

时间:2017-07-03 08:34:32

标签: java printing println system.out

在一系列print语句中,如何只打印一次特定的语句?

示例:

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();
}

这实际上将日志附加到“filepath”中提到的CSV文件中,我只想打印“pw.println(”A,B,C,D,E,F,G,“)行;”虽然我多次调用该程序,但只有一次。

我有办法做到这一点吗?

2 个答案:

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

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

在您发布代码时编辑代码并添加您需要执行的检查

相关问题