1

システムの現在の日付と時刻をログ ファイル (コンピューターの起動時にバッチ ファイルによって実行される) に追加する Java プログラムを作成しようとしています。これが私のコードです。

public class LogWriter {

    public static void main(String[] args) {

        /* open the write file */
        FileOutputStream f=null;
        PrintWriter w=null;

        try {
            f=new FileOutputStream("log.txt");
            w=new PrintWriter(f, true);
        } catch (Exception e) {
            System.out.println("Can't write file");
        }

        /* replace this with your own username */
        String user="kumar116";
        w.append(user+"\t");

        /* c/p http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/ */
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        w.append(dateFormat.format(date)+'\n');

        /* close the write file*/
        if(w!=null) {
            w.close();
        }

    }

}

問題は、ファイルに :) を追加していないことです。誰かがここで何が問題なのか指摘できますか?

前もって感謝します。

4

2 に答える 2

1

PrintWriter#appendは、ファイルにデータを追加しません。write代わりに、を使用してダイレクトを実行しWriterます。FileOutputStream追加フラグを使用してコンストラクターを宣言する必要があります。

f = new FileOutputStream("log.txt", true);
w = new PrintWriter(f); // autoflush not required provided close is called

appendメソッドは引き続き使用できますが、改行文字を追加する必要がない方が便利ですprintln

w.println(dateFormat.format(date));

close が呼び出された場合、コンストラクターの autoflush フラグはPrintWriter必要ありません。ブロックcloseで表示する必要があります。finally

于 2013-04-30T00:03:32.477 に答える
0

コンストラクターは、ファイルに追加するかどうかを決定するためのPrintWriterパラメーターを取りません。自動フラッシュを制御します。

(ファイルに追加するかどうかを制御できる) を作成し、FileOutputStreamそのストリームをPrintWriter.

try {
    f=new FileOutputStream("log.txt", true);
    w=new PrintWriter(f, true);  // This true doesn't control whether to append
}
于 2013-04-30T00:03:22.567 に答える