我试图增加一个文本文件名,以便创建的所有文本文件都有一个唯一的名称,并将按升序排列。这是我到目前为止的代码。我希望你能理解我在这里尝试的逻辑。问题是程序是锁定还是此代码什么都不做。谢谢。
增加是0的全局int
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();
}
}
}
用代码解释我的评论
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
在更新int变量increase
时,不要更改File file
。这就是为什么你以无限循环结束的原因。
我为我的项目要求编写的代码适用于所有/没有扩展。希望有所帮助!
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);
}
}