gpt4 book ai didi

java - 在java中增加文本文件名

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:38 25 4
gpt4 key购买 nike

我正在尝试递增文本文件名,以便创建的所有文本文件都将具有唯一的名称并按升序排列。这是我到目前为止的代码。我希望你能理解我在这里尝试的逻辑。问题要么是程序正在锁定,要么是这段代码什么都不做。谢谢。

increase是一个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();
}
}
}

最佳答案

用代码解释我的评论

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

关于java - 在java中增加文本文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com