Reputation: 155
Im trying to increment a text file name so that all text files created will have a unique name and will be in ascending order. Here is the code I've got so far. I hope you can understand the logic of what I am attempting here. The problem is either that the program is locking up or this code does nothing. Thanks.
increase is a global int of 0
String name = String.valueOf(increase);
File file = new File("E:\\" + name + ".txt");
while(file.exists()){
increase++;
if(!file.exists()) {
try {
String content = textfile.toString();
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
}catch (IOException e){
e.printStackTrace();
}
}
}
Upvotes: 3
Views: 3457
Reputation: 628
The code below I wrote for my project requirement which works with all/without extensions. Hope that helps!
public static File getValidFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return file;
} else {
int extAt = filePath.lastIndexOf('.');
String filePart = filePath;
String ext = "";
if(extAt > 0) { //If file is without extension
filePart = filePath.substring(0, extAt);
ext = filePath.substring(extAt);
}
if (filePart.endsWith(")")) {
try {
int countStarts = filePart.lastIndexOf('(');
int countEnds = filePart.lastIndexOf(')');
int count = Integer.valueOf(filePart.substring(countStarts + 1, countEnds));
filePath = filePart.substring(0, countStarts + 1) + ++count + ")" + ext;
} catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
filePath = filePart + "(1)" + ext;
}
} else {
filePath = filePart + "(1)" + ext;
}
return getValidFile(filePath);
}
}
Upvotes: 1
Reputation: 613
to explain my comment with code
String name = String.valueOf(increase);
File file = new File("E:\\" + name + ".txt");
while(file.exists()){
increase++;
// reassign file this while will terminate when #.txt doesnt exist
name = String.valueOf(increase);
file = new File("E:\\" + name + ".txt");
} // the while should end here
// then we check again that #.txt doesnt exist and try to create it
if(!file.exists()) {
try {
String content = textfile.toString();
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
}catch (IOException e){
e.printStackTrace();
}
// you had a extra close bracket here causing the issue
}
// this program will now create a new text file each time its run in ascending order
Upvotes: 1
Reputation: 1249
While you update your int variable increase
, you don't change your File file
. That's why you end in an infinite loop.
Upvotes: 1