【问题标题】:Add suffix to filename if file already exist instead of overwriting it如果文件已经存在而不是覆盖它,则为文件名添加后缀
【发布时间】:2015-03-10 01:50:45
【问题描述】:

我正在保存一个上传的文件,如下所示:

UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
    dir.mkdir();
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName());
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();

但我的问题是何时在文件夹 D:/FileUpload 中上传一次文件相同的旧文件。在上述功能中,它将删除旧文件。第一次示例,我上传文件:test.doc(旧文件)。然后我上传另一个同名文件:test.doc(新文件)。在文件夹 FileUpload 将有一个文件是 test.doc(新文件)。我希望在窗口操作系统中处理类似的函数是:新文件将是 test (2).doc。我该如何处理?所有情况:D:/FileUpload 有很多文件:test.doctest (1).doctest (2 ).doc, test (a).doc,...... 我想我们只是检查格式 ....(int).doc。该新文件将是: test(3).doc(忽略test(a).doc

【问题讨论】:

    标签: java file-io overwrite


    【解决方案1】:

    也许你正在寻找这样的东西?我列出了您目录中的文件,将每个文件的名称与您的文件名进行比较。如果名称匹配,则增加计数。然后,当您开始创建文件时,请在其名称中包含计数。

    UploadItem item = event.getUploadItem();
    File dir = new File("D:/FileUpload");
    if (!dir.exists()) {
        dir.mkdir();
    }
    String [] files = dir.list();
    int count = 0;
    
    for(String file : files) {
      if (file.startsWith(item.getFileName()) {
        count++;
      }
    }
    
    File bfile = new File("D:/FileUpload" + "/" + item.getFileName() + "(" + count + ")");
    OutputStream outStream = new FileOutputStream(bfile);
    outStream.write(item.getData());
    outStream.close();
    

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 2015-02-02
      • 2015-07-22
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      相关资源
      最近更新 更多