Java 检查文件夹是否存在,如果存在,请添加";新文件夹2“;

Java 检查文件夹是否存在,如果存在,请添加";新文件夹2“;,java,ajax,Java,Ajax,我继承了一个web应用程序。我是Java新手,所以不要把我痛打一顿。我使用以下方法将新文件夹添加到附件页。用户可以在页面上创建新文件夹并重命名,但如何检查“新文件夹”是否已存在,如果已存在,如何创建“新文件夹(2)”或“新文件夹(3)”等 以下是我的附件servlet中的方法: protected void newFolderAction(HttpServletRequest request, HttpServletResponse response, User user, String f

我继承了一个web应用程序。我是Java新手,所以不要把我痛打一顿。我使用以下方法将新文件夹添加到附件页。用户可以在页面上创建新文件夹并重命名,但如何检查“新文件夹”是否已存在,如果已存在,如何创建“新文件夹(2)”或“新文件夹(3)”等

以下是我的附件servlet中的方法:

  protected void newFolderAction(HttpServletRequest request, HttpServletResponse response, User user, String folderId) throws UnsupportedEncodingException,
                IOException {
    String key = request.getParameter("key");
    String value = request.getParameter("value");
    Attachment parent = AttachmentRepository.read(UUID.fromString(key));
    String path = parent.getPath();

    logger.debug("newFolder: key=" + key + " value=" + value + " path=" + path);
    if (AttachmentRepository.read(path + "New Folder/") == null) {
        long size = 0L;
        boolean isFolder = true;
        boolean isPicture = false;
        UUID attachmentId = UUID.randomUUID();
        Attachment attachment = new Attachment(attachmentId, UUID.fromString(folderId), user.getUnitId(), UUID.fromString("11111111-1111-1111-1111-111111111111"), path + "New Folder/", size, isFolder, isPicture,
                        "", "0", "0", user.getName(), new Date());
        AttachmentRepository.add(attachment);

        File directory = new File(Settings.instance().getAttachmentsDir() + "/" + attachment.getPath());
        directory.mkdirs();
    }

    Attachment rootAttachment = AttachmentRepository.read(folderId + "/");
    writeJsonAttachmentsTree(response, user, request.getRequestURI(), rootAttachment);
}

Java中没有为您创建目录的自定义内置函数。如果所需名称已经存在,您应该自己实现一个

public static void main(String[] args) {

    File folderPath = new File("c:\\New Folder");

    // Check whatever folderPath exists
    System.out.println(folderPath.getPath() + " is directory ? " + folderPath.isDirectory());

    // Create new folder
    File folderCreated = createFolder(folderPath);
    System.out.println("The new directory path is: " + folderCreated.getPath());

    // Check whatever folderPath exists
    System.out.println(folderCreated.getPath() + " is directory ? " + folderCreated.isDirectory());
}

public static File createFolder(File path) {
    File pathNum = new File(path.getPath());
    String num = "";
    int i = 1;
    do {
        pathNum = new File(path.getPath() + num);
        num = "(" + ++i + ")";
    } while (!pathNum.mkdir());
    return pathNum;
}