在java中增加文本文件名

时间:2014-02-20 00:17:20

标签: java int increment

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

增加是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();
                }
        }
    }

3 个答案:

答案 0 :(得分:1)

在更新int变量increase时,不会更改File file。这就是你以无限循环结束的原因。

答案 1 :(得分:1)

用代码解释我的评论

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

答案 2 :(得分:0)

下面为我的项目要求编写的代码可与所有/不带扩展一起使用。希望有帮助!

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);
    }
}