Search code examples
javasavefilewriterprintwriter

Function "writeFile(String Text)" Doesn't work the second time used


Before you call this a duplicate, please acknowledge the following facts:

  1. There are no boolean values.
  2. After I read the text files MANUALLY, they were missing the second String supposed to be written to the file.

Here is the code that is supposed to matter:

package StorageBox;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class StorageBox02 {
    String FileName;
    PrintWriter pw;
    Scanner sc;
    public StorageBox02(){

    }
    public StorageBox02(String FileName) {
        this.FileName = FileName;
    }
    public void writeFile(String Text) throws IOException{
        FileWriter fw = new FileWriter(FileName);
        pw = new PrintWriter (fw);
        pw.write(Text + "\t");
        pw.close();
    }

}

The second string is what is intended to happen when I run the writeFile method twice.


Solution

  • After I read the text files MANUALLY, they were missing the second String supposed to be written to the file.

    Seems like you are trying to append to the previously written file. In that case, you need to open the file in append mode by passing true to the PrintWriter.

    For Example, new PrintWriter(fw, true);