简体   繁体   中英

writing log to text file for objects java

This is my first attempt at creating a logger for an Object class. I intend the logger to write to a text file. Currently only the last Log.println line is readable from the text file.

How can I get the logger to write all the print lines from the Object class.

Object class:

import java.io.Serializable;

public class Battle implements Serializable{

    public static void main(String[] args) {

        Log.println("******Round******\n");
        Log.println("New Turn\n");
    }
}

Logger:

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Log {
    private static FileWriter log = null;
    private static boolean fileOut = true;

    public static void println(String output) {
        print(output+"\n");
    }

    public static void print(String output) {
        if (fileOut) {

            File file = new File("file.txt");
            try {

                ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream(file));

                System.out.println(output);
                objectOut.writeObject(output);

                objectOut.flush();
                objectOut.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.print(output);
        }
    }
    public static void setConsoleOut() {
        fileOut = false;
    }
}

Current text file output:

’
New Turn

Intended text file output:

******Round******


New Turn

You overwrite the file on every call which is why you only see the last entry.

You can use a FileWriter rather than an ObjectOutputStream as the former allows you to append the data written.

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

Alternately, you can simply redirect the standard output stream to a file and use System.out.println("xxx");

How Can I Pipe the Java Console Output to File Without Java Web Start?

Use a writer instead:

PrintWriter objectOut = new PrintWriter(new BufferedWriter(new FileWriter(file)));

Then simply write your object toString() to it:

objectOut.println(output);

What is happening in the public static void print(String output) { method is that the underlying log file contents are truncated on each call to the method. This is due to the new FileOutputStream(file) constructor variant being used. This can be fixed by using public FileOutputStream(String name, boolean append) instead, where the second argument boolean append will ensure that bytes will be written to the end of the file rather than the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM