当我在程序中创建新文件夹时,我遇到了一个小的意外问题。这里是我的方法,其中创建我的目录:如何防止我的方法创建名为“null”的文件夹
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”的文件夹,而不管。我如何防止它发生?
我的临时解决方案(尽管非常草率)是让用户创建该文件夹(无论是否意外),并让它成为我的程序将打印出一个错误,并不会创建它,如果这个名称的文件夹在那个目录中已经存在。
编辑:同样的事情发生在你按取消。 编辑2:添加了提示方法。
你没有张贴popUp.newCategoryPrompt()的代码,所以这是什么实际上做?必须有一种方法来检查此方法是否用户取消,并返回一个可以评估的布尔值false,以查看是否需要创建目录? – copeg 2015-04-02 15:50:26
@copeg刚刚编辑它。 – Lotix 2015-04-02 15:59:14