Java: 如何找到最大的文件编号并递增?

Java: How do you find the highest file number and increment it?

所以,我写了一个代码来创建一个文件,但首先它使用一个 if 语句来检查一个文件是否存在,如果存在,它应该将一个整数增加 1,尽管我觉得我需要到 运行 增量后的检查,但现在我至少应该得到 file1 和 file2。

public void createNewCSV() throws IOException {

    int stepped = 1;
    //TODO: Find the highest number in the series of files
    File file = new File("_GAMES/" + getSaveName() + "_" + stepped + ".csv");

    //TODO: If the filename matches create a file-[higest number + 1].csv
    if (file.exists()) {
        System.out.println("File exists");
        Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + (stepped++) + ".csv");
        Files.createDirectories(filePath.getParent());
        try {
            final BufferedWriter out = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("File don't exists");
        Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + stepped + ".csv");
        Files.createDirectories(filePath.getParent());
        try {
            final BufferedWriter out = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这些打印件告诉我文件是否正确存在。我有一种感觉,使用 int stepped = 1;是它分崩离析的地方。有谁知道我怎样才能让 stepped++ 工作?

尝试预增量 'stepped'。改变这个

Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + (stepped++) + ".csv");

至此

Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + (++stepped) + ".csv");