javaprintwriter

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?


Solution

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