Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

So, I’ve written a code to create a file, but first it uses an if statement to check if a file exists and if it does it should increase an integer by 1, though I have a feeling I need to run the check after the increment, but for now I should at least get file1 and 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();
        }
    }
}

The prints tell me if the file does or doesn’t exist properly. I have a feeling that using int stepped = 1; is where it’s falling apart. Does anyone know how I can get the stepped++ to work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try pre increment ‘stepped’. Change this

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

to this

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading