user2786754
user2786754

Reputation: 139

Not writing to text file

I currently am having problems writing to the text file in my code, the entirety of the program is hit and everything will print out to the console. no errors. But the file is empty. Any suggestions?

public textFiles(String filePath)
{
File file = new File(filePath);

try{
    fstream = new FileWriter(filePath,true);
}
catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
     out = new BufferedWriter(fstream);
                System.out.println("try");

        addToText("WOOOOHOOO");
          System.out.println(file.exists());


}
public void addToText(String Line)
{
    try {
        out.write(Line);
        out.newLine();
    } catch (IOException e) {
        System.err.println("writing Error");
    }
    System.out.println("SHOULDA F****** WORKED");
}

Upvotes: 0

Views: 120

Answers (2)

Sandeep Sehrawat
Sandeep Sehrawat

Reputation: 586

Try this code to write a .txt file in any drive.

                  try
                  {
                  String ss="html file write in java";
                  File file= new File("F:\\inputfile\\aa.txt");
                  FileWriter fwhn= new FileWriter(file);
                  fwhn.write(ss);
                  fwhn.flush();
                  }
                  catch(Exception ex)
                  {

                  }

Upvotes: -1

Michael Berry
Michael Berry

Reputation: 72254

You're never closing the stream, and so probably never flushing the stream either - the text essentially gets cached when you print it out, and gets flushed to the file in chunks (usually chunks that are much bigger than what you're writing, hence the lack of output.)

Make sure you close the stream when you're done (fstream.close();), and it should work fine (the stream will automatically flush to clear any output when it's closed).

Upvotes: 4

Related Questions