當我在程序中創建新文件夾時,我遇到了一個小的意外問題。這裏是我的方法,其中創建我的目錄:如何防止我的方法創建名爲「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