1

I want to check if a text file exists, and set a PrintWriter to write in it. for now any new PrintWriter instance overwrite the last one. My main:

TextFileForStatus textFile = new TextFileForStatus();
int startingIndex = 1; 

try{
    String output = textFile.readIndex();
    System.out.println("In file: " + output);
    if(output == null)
    {
        textFile.writeToFile(Integer.toString(startingIndex));
    }
    else {
        System.out.println("output: " + output);
        startingIndex = Integer.parseInt(output);
    }
} catch(ReaderException RE){
    RE.getMessage().toString();
}catch(Exception EX){
    EX.getMessage().toString();
}

and the class I created to create the file:

public class TextFileForStatus {

    private final String fileName = "status";
    private final String Format =  "UTF-8";
    private BufferedReader reader = null;
    private PrintWriter writer = null;

    public TextFileForStatus() throws FileNotFoundException, UnsupportedEncodingException {
        writer = new PrintWriter(fileName, Format);
        reader = new BufferedReader(new FileReader(fileName));
    }
    public void writeToFile(String currentStatus){
        writer.println(currentStatus);
        System.out.println("writer wrote: "+ currentStatus + " to file");
        writer.flush();
    }
    public String readIndex() throws IOException{
        String indexInFile = "";
        while((indexInFile = reader.readLine())!=null){
            indexInFile += reader.readLine();
        }
        return indexInFile;
    }
}

Can I use the text file that already exists?

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114
  • This code will not compile – fge Nov 19 '15 at 12:43
  • 1
    Possible duplicate of [How to append text to an existing file in Java](http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Mad Physicist Nov 19 '15 at 12:46
  • I wrote only the relevant parts. the code compiles and writes to file. – Itsik Mauyhas Nov 19 '15 at 12:46
  • 1
    Use [`Files.newBufferedWriter(... StandardOpenOption.WRITE, APPEND)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newBufferedWriter%28java.nio.file.Path,%20java.nio.charset.Charset,%20java.nio.file.OpenOption...%29) – Joop Eggen Nov 19 '15 at 12:47

2 Answers2

2

You can use new File(fileName).exists() to check if a file exists or not. So you may want to try:

public class TextFileForStatus {

    private final String fileName = "status";
    private final String Format = "UTF-8";
    private BufferedReader reader = null;
    private PrintWriter writer = null;
    private boolean fileExists; // flag

    public TextFileForStatus() throws FileNotFoundException, UnsupportedEncodingException {
        fileExists = new File(fileName).exists();
        writer = new PrintWriter(fileName, Format);
        reader = new BufferedReader(new FileReader(fileName));
    }

    public void writeToFile(String currentStatus) {
        if (fileExists) {
            writer.println(currentStatus);
            System.out.println("writer wrote: " + currentStatus + " to file");
            writer.flush();
        }
    }

    public String readIndex() throws IOException {
        if (!fileExists) return "";

        String indexInFile = "";
        while ((indexInFile = reader.readLine()) != null) {
            indexInFile += reader.readLine();
        }
        return indexInFile;
    }
}
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
Bon
  • 3,073
  • 5
  • 21
  • 40
1

Use JDK7 Files:

public void writeToFile(String path, String fileName, String status) throws Exception {
    String text = "writer wrote: "+ status + " to file";
    Path p = Paths.get(path, fileName);
    if (Files.isWritable(p)) { //checks for existence too
        Files.write(p, text.getBytes(), StandardOpenOption.APPEND); // see https://docs.oracle.com/javase/tutorial/essential/io/file.html#openOptions
    }
}

Check OpenOption for writing options.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
s.ijpma
  • 930
  • 1
  • 11
  • 23