0

I want my program to create a new text file unless one already exists. Any way, I want to print one line to the file for each time the program is run. The file is created but no data is saved to it. Why?

File fileName = new File("fileName");

try {
    if (fileName.exists())
    {
        filePrinter = new PrintWriter(new FileOutputStream(fileName));
    }
    else
    {
        filePrinter = new PrintWriter(new FileOutputStream(fileName, true));
    }

} catch (FileNotFoundException e1) 
    {
        e1.printStackTrace();
    }

//irrelevant code


filePrinter.println("some text" + integerValue + "then more text");
filePrinter.close();

2 Answers2

0

I would recommend flushing out the content before closing it.

filePrinter.flush(); 

if this doesnt work try the following:

filePrinter = new FileWriter(new File(fileName));
filePrinter.write("some text" + integerValue + "then more text");
filePrinter.flush();
filePrinter.close();
Ashish
  • 1,121
  • 2
  • 15
  • 25
0

The problem was outside the posted code, all apologies. The problem was that the

    //irrelevant code

Contained instructions to reset the program upon certain conditions. Those conditions were always true, and so the filePrinter.println() code was never reached.

Thank you for all input.