CodeMed
CodeMed

Reputation: 9191

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")
    }
}

Upvotes: 0

Views: 5519

Answers (3)

Charu Khurana
Charu Khurana

Reputation: 4551

Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or Use flush() and close() when you're done writing

Upvotes: 1

user2464620
user2464620

Reputation: 68

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

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117597

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

Upvotes: 1

Related Questions