【问题标题】:Save file with number increment in last of the file在文件的最后保存带有数字增量的文件
【发布时间】:2018-01-09 13:23:30
【问题描述】:

我正在努力让这段代码正常工作,基本上这个想法是让应用程序保存文件,如果文件存在,那么我希望它在末尾添加一个数字,例如:file.txt,@ 987654322@,file2.txt

但它会保存第一个文件,然后应用程序崩溃,这与 while 循环有关,我还没有尝试过 for 函数。

// txtTiltetosave = The Title that is used by the save function (this works)

int num = 0;
File myFile = new File("mydir);
if (myFile.exists()) {
       while (myFile.exists()) {
           txtTitletosave = "file"+(num++);
       }
} else {
       txtTitletosave = "file";
}

任何帮助或建议将不胜感激。谢谢

【问题讨论】:

  • 你不需要while循环。
  • 那你有什么建议?如果没有 while 循环,它只会生成两个文件。例如:file.txt、file1.txt。它不会增加
  • 你甚至漏掉了一个撇号,很难弄清楚你想要什么。
  • 是吗?我只是想在每次保存时增加的保存文件末尾添加一个数字。例如:file.txt、file1.txt、文件 2.txt 等
  • while (myFile.exists()) { txtTitletosave = "file"+(num++); 这是一个无限循环。它永远不会结束,因为条件没有任何变化。

标签: java android loops android-studio


【解决方案1】:

感谢所有帮助这两个答案的人,但对我来说没有用,但他们确实给了我一个想法,这正是我想要的。

File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/mydir" + "file.txt");
  if (!myFile.exists()) {
        txtTitletosave = "file";
  } else {
       int count = new File(Environment.getExternalStorageDirectory() + File.separator + "/mydir").list().length;
       txtTitletosave = "file"+count;
  }

【讨论】:

    【解决方案2】:

    你可以试试这个—— 最初使用此代码找出给定目录中有多少文件,如果没有,则创建一个新文件。

    File file = new File("C:/MyFolder/");
    if(!file.exists()){
      txtTitletosave = "file";
    }
    else {
    int count = file.listFiles().length;
    txtTitletosave = "file"+count;
    }
    

    如果这有帮助,请告诉我,但还没有尝试过。

    【讨论】:

    • 我以后得试试。但我不明白为什么那行不通。逻辑上。谢谢
    • 很高兴它有帮助,如果它适合你,请接受答案:)
    【解决方案3】:

    使用下面的代码对你有帮助

       File myFile = new File("mydir");
        String txtTitletosave;
        if (myFile.exists()) {
            String [] array = myFile.getName().split("\\.");
            String fileName = array[0];
            String lastNumber = fileName.substring(fileName.length() -1);
            int numberToIncrease = Integer.parseInt(lastNumber);
    
                txtTitletosave = "file"+(++numberToIncrease);
    
        } else {
            txtTitletosave = "file";
        }
    

    即使代码很长,也可以重构。但为了清楚起见,我已经一步一步地写了。希望对你有所帮助。

    【讨论】:

    • 当我有机会我会尝试不明白为什么那行不通。谢谢
    猜你喜欢
    • 2021-12-04
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多