gpt4 book ai didi

java - 如何防止我的方法创建名为 "null"的文件夹

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

在程序中创建新文件夹时,我遇到了一个意外的小问题。这是我创建目录的方法:

public void createDirectory() {

directory = new File("C:/Users/Lotix/Desktop/TestFolder/"
+ categoryName);
boolean isDirectoryCreated = directory.mkdir();

if (isDirectoryCreated) {

System.out.println("Created new directory in: " + directory);

} else if (directory.exists()) {

System.out.println("Category already exists!");

}

}

这是我的监听器方法,该方法被调用:

if (e.getSource() == addButton) {

System.out.println("Add Button Clicked");
botTextArea.setText("");
botTextArea.append("Adding new category...");

popUp.newCategoryPrompt();
System.out.println(popUp.getNewCategoryName());
Category cat = new Category(popUp.getNewCategoryName(), "test tag" );
cat.createDirectory();

}

以及提示方法本身:

// Prompt to enter name of the new category
public void newCategoryPrompt() {

JFrame newCatFrame = new JFrame();
newCategoryName = JOptionPane.showInputDialog(newCatFrame,
"Enter the name of new category");

}

具体问题是什么?

程序应该在现有目录中创建一个文件夹。但是,当用户决定关闭该提示而不为新文件夹指定名称时,它会创建一个名为“null”的文件夹。我该如何防止它发生?

我的临时解决方案(虽然很草率)是让用户创建该文件夹(无论是否意外)并让它这样,因为我的程序将打印出错误并且不会创建它,如果具有此类名称的文件夹在该目录已经存在。

编辑:当您按取消时会发生同样的情况。EDIT2:添加了提示方法。

最佳答案

尝试

Category cat = new Category(popUp.getNewCategoryName(), "test tag" );
if(cat.getCategoryName() != null)
cat.createDirectory();

您需要将 getCategoryName() 更改为 Category 类中类别名称的 getter。

关于java - 如何防止我的方法创建名为 "null"的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417120/

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