在 Java 中下载同名附件而不覆盖

Download attachments with same name without overwriting in Java

根据我的要求,我需要从收件箱中下载一个文件到指定的目录,过一段时间如果有同样的文件进来,我需要将同一个文件保存到同一个目录,但名称不同,这里不应覆盖以前的文件意味着文件必须以相同的名称保存在同一目录中(这里我有一个假设,例如,如果我的文件是 abc.txt,修改后,如果我下载修改后的文件,它可以是保存为 abc(1).txt )。我该如何解决我的问题?任何人都可以帮助我解决 JAVA 中的这个问题。下面是我的代码,但它覆盖了同一个文件。

if (contentType.contains("multipart")) {
  // this message may contain attachment
  Multipart multiPart = (Multipart) message.getContent();
  for (int i = 0; i < multiPart.getCount(); i++) {
    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {

      // save an attachment from a MimeBodyPart to a file
      String destFilePath = "F:/unprocessed/"+part.getFileName();
      InputStream input = part.getInputStream();
      BufferedInputStream in = null;
    in = new BufferedInputStream(input);

      FileOutputStream output = new FileOutputStream(destFilePath);

      byte[] buffer = new byte[4096];

      int byteRead;

      while ((byteRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, byteRead);
      }

      System.out.println("FileOutPutStream is Being Closed");
      output.close();

    }
  }

}

如前所述,您需要检查现有文件。这是一种方法:

public String getUniqueFileName(String input) {
    String base = "F:/unprocessed/";

    String filename = base+input;

    File file = new File(filename);
    int version = 0;
    while (file.exists()) {
        version++;
        String filenamebase = filename.substring(0, filename.lastIndexOf('.'));
        String extension = filename.substring(filename.lastIndexOf('.'));
        file = new File(filenamebase+"("+ version+")"+extension);
    }
    return file.getAbsolutePath();
}

然后将 destFilePath 的赋值更改为调用此方法:

String destFilePath = getUniqueFileName(part.getFileName());