Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

java check if text file exists without overwrite

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?

Upvotes: 1

Views: 4106

Answers (2)

s.ijpma
s.ijpma

Reputation: 940

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.

Upvotes: 1

Bon
Bon

Reputation: 3103

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

Upvotes: 2

Related Questions