gpt4 book ai didi

java - 检查文件夹是否存在,如果存在则添加 "New Folder 2"

转载 作者:行者123 更新时间:2023-12-01 12:49:27 25 4
gpt4 key购买 nike

我有一个继承的 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;
}

关于java - 检查文件夹是否存在,如果存在则添加 "New Folder 2",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24351169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com