有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

printwriter java检查文本文件是否存在而不覆盖

我想检查文本文件是否存在,并设置一个PrintWriter来写入它。现在,任何新的PrintWriter实例都会覆盖上一个实例。 我的主要意见是:

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

以及我为创建文件而创建的类:

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

我可以使用已经存在的文本文件吗


共 (2) 个答案

  1. # 1 楼答案

    使用JDK7文件:

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

    检查OpenOption以获取写入选项

  2. # 2 楼答案

    您可以使用new File(fileName).exists()检查文件是否存在。因此,您可能需要尝试:

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