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?
Try pre increment 'stepped'. Change this
Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + (stepped++) + ".csv");
to this
Path filePath = Paths.get("_GAMES/" + getSaveName() + "_" + (++stepped) + ".csv");