【问题标题】:Java create multiple new filesJava创建多个新文件
【发布时间】:2019-01-31 14:21:09
【问题描述】:

我在这里看到了这个问题How to create a file in a directory in java?

我有一个创建二维码的方法。该方法被调用多次,取决于用户输入。

这是一个代码sn-p:

String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);

问题:如果用户输入“2”,那么这个方法会被触发两次。 结果,第一个 qrCODE.png 文件将被第二个 qrCODE.png 替换,所以第一个丢失了。

如何生成多个不同名称的二维码,如 qrCODE.png 和 qrCODE(2).png

我的想法:

if (!myFile.exists()) {
    try {
        myFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有什么建议吗?

编辑:我通过使用 for 循环并在每个循环步骤中增加文件名中的数字来解决它。

【问题讨论】:

  • 为什么不在保存之前测试文件是否存在,如果存在则递归尝试使用 filename+(2) ?
  • File.createTempFile("qrCODE", ".png", new File("/Users/Test"));
  • 可能使用文件名中的时间戳:System.currentMillis() 或使用UUID

标签: java file qr-code


【解决方案1】:

您可以创建更多文件,例如。如下

int totalCount = 0; //userinput

String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";

for(int counter = 0; counter < totalCount; counter++){
    int size = 250;
    //tbd
    File myFile = new File(filePath+fileName+counter+"."+fileType);
    /*
       will result into files qrCODE0.png, qrCODE1.png, etc.. 
        created at the given location
    */
}

顺便说一句,添加检查文件是否存在也是一个好点。

{...}
 if(!myFile.exists()){
    //file creation
    myFile.createNewFile()
 }else{
   //file already exists
 } 
{...}

【讨论】:

    【解决方案2】:

    您可以在创建文件之前检查/Users/Test direcroty。

    String dir = "/Users/Test";
    String pngFileName = "qrCode";
    
    long count = Files.list(Paths.get(dir))      // get all files from dir
        .filter(path -> path.getFileName().toString().startsWith(pngFileName))   // check how many starts with "qrCode"
        .count();
    
    pngFileName = pngFileName + "(" + count + ")";   
    

    【讨论】:

      【解决方案3】:

      你解决问题的想法很好。我的建议是将filePath 变量分解为几个变量,以便更轻松地操作文件名。然后,您可以引入一个fileCounter 变量,该变量将存储创建的文件数,并使用该变量来操作文件名。

      int fileCounter = 1;
      String basePath = "/Users/Test/";
      String fileName = "qrCODE";
      String fileType = ".png";
      
      String filePath = basePath + fileName + fileType;
      File myFile = new File(filePath);
      

      然后您可以检查文件是否存在,如果存在,您只需为 filePath 变量赋予一个新值,然后创建新文件

      if(myFile.exists()){
          filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
          myFile = new File(filePath);
      }
      createFile(myFile);
      

      你就完成了!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-14
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        相关资源
        最近更新 更多