代码之家  ›  专栏  ›  技术社区  ›  horribly_n00bie

Java:如何找到最高的文件号并增加它?[重复]

  •  0
  • horribly_n00bie  · 技术社区  · 3 年前

    所以,我写了一个代码来创建一个文件,但首先它使用一个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++工作吗?

    1 回复  |  直到 3 年前
        1
  •  2
  •   Michel Fortes    3 年前

    尝试“步进”预增量。改变这个

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

    对这个

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