0

I have written a code. But I found everytime it written the error into log file, it will totally cover the existed file, not to appended after it. What happened...

try {
            int s = 1 / 0;
        } catch (Exception e) {
            try {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sd = new SimpleDateFormat("yyyy_MM_dd");
                String s = sdf.format(d);
                String day = sd.format(d);

                PrintStream ps = new PrintStream("src/log/"+day+"_Exception.log");
                ps.println(s);

                System.setErr(ps);
            } catch (Exception e2) {
            }
            e.printStackTrace(System.err);
        }
Hunter_JW
  • 3
  • 2
  • Read the javadocs *file - The file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created.* – Scary Wombat Dec 02 '19 at 06:30
  • `PrintStream ps = new PrintStream("src/log/"+day+"_Exception.log", true);` will allow to append in existing file. – Sudhir Ojha Dec 02 '19 at 06:33
  • @SudhirOjha Thanks for comment...but it still didn't work... IDEA reported "Cannot resolve constructor 'PrintStream(java.lang.String, boolean)'". By the way this is using JDK8. – Hunter_JW Dec 02 '19 at 06:48

1 Answers1

0

When a new PrintStream with a String argument is created, the argument is interpreted as the path of a new FileOutputStream to create.

So the sentence:

PrintStream ps = new PrintStream("src/log/"+day+"_Exception.log");

bsically creates a new FileOutputStream with the default "append" flag, that is false.

To realize the append that you want, you have to modify your code as follow:

try {
    int s = 1 / 0;
} catch (Exception e) {
    try {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy_MM_dd");
        String s = sdf.format(d);
        String day = sd.format(d);

        FileOutputStream fos = new FileOutputStream("src/log/" + day + "_Exception.log");
        PrintStream ps = new PrintStream(fos);

        ps.println(s);

        System.setErr(ps);
    } catch (Exception e2) {
    }
    e.printStackTrace(System.err);
}
Andrea Annibali
  • 379
  • 2
  • 5