简体   繁体   中英

using PrintWriter to write strings to log file

I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?

public class MyMainClass{    
    PrintWriter output;

    MyMainClass(){    
        try {output = new PrintWriter("somefile.txt");}    
        catch (FileNotFoundException e1) {e1.printStackTrace();}    
        anotherMethod();
    }    

    void anotherMethod(){
        output.println("print some variables");
        MyOtherClass other = new MyOtherClass();
        other.someMethod(this);
    }
}

public class MyOtherClass(){
    void someMethod(MyMainClass mmc){
        mmc.output.println("print some other variables")
    }
}

Use the other constructor:

output = new PrintWriter(new FileWriter("somefile.txt"), true);

According to JavaDoc :

public PrintWriter(Writer out, boolean autoFlush)

Creates a new PrintWriter.

Parameters:

out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer

使用其他构造函数new PrintWriter(new PrintWriter("fileName"), true)进行自动刷新数据,或在完成编写后使用flush()close()

How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine

public static void writeToLog(String inString)
{
    File f = new File("yourFile.txt");
    boolean existsFlag = f.exists();

    if(!existsFlag)
    {
        try {
            f.createNewFile();
        } catch (IOException e) {
            System.out.println("could not create new log file");
            e.printStackTrace();
        }

    }

    FileWriter fstream;
    try {
        fstream = new FileWriter(f, true);
         BufferedWriter out = new BufferedWriter(fstream);
         out.write(inString+"\n");
         out.newLine();
         out.close();
    } catch (IOException e) {
        System.out.println("could not write to the file");
        e.printStackTrace();
    } 


    return;
}

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