我在写文件管理器的时候有个功能是创建文件夹,第一次创建很正常,但是立马接着创建下一个文件夹就失败了,没有任何异常抛出,求解

解决方案 »

  1.   

    /*
     * @创建文件夹
     * */
    public boolean mkDir(String path){
    File dir = new File(path);
    if(dir.exists()){
    System.out.println("文件夹已经存在!");
    return false;
    }
    if(!path.endsWith(File.separator)){
    path = path + File.separator;
    if(new File(path).mkdir()){
    System.out.println("创建目录:"+path+"成功!");
    return true;
    }
    }
    return false;
    }
    class AddDir implements ActionListener{
    public void actionPerformed(ActionEvent e) {
    IconNode node = (IconNode) pathTree.getLastSelectedPathComponent();
    TreePath lastPath = pathTree.getSelectionPath();
    pathTree.fireTreeExpanded(lastPath);
    String name = JOptionPane.showInputDialog("请输入文件夹的名称:", "新建文件夹 ");
    if(name!=""){
    IconNode newNode = new IconNode(getFolderIcon(),name);
    newNode.setAllowsChildren(false);
    System.out.println("创建目录:"+getNodePath(node)+name);
    if(mkDir(getNodePath(node)+name)){
    if(!node.getAllowsChildren())
    node.setAllowsChildren(true);
    dtm.insertNodeInto(newNode, node, node.getChildCount());
    pathTree.setSelectionPath(new TreePath(newNode.getPath()));
    pathTree.scrollPathToVisible(new TreePath(newNode.getPath()));
    }
    else{
    JOptionPane.showConfirmDialog(null, "文件夹创建失败!","文件夹创建警告 ",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null);
    }
    }
    }
    }
      

  2.   


    象你这样写逻辑上是有问题的 if (!path.endsWith(File.separator)) {
    path = path + File.separator;
    if (new File(path).mkdir()) {
    System.out.println("创建目录:" + path + "成功!");
    return true;
    }
    }
    return false;如果path以"\"结尾,就不会被创建而直接返回false改成下面这样: public boolean mkDir(String path) {
    File dir = new File(path);
    if (dir.exists()) {
    System.out.println("文件夹已经存在!");
    return false;
    }
    if (!path.endsWith(File.separator)) {
    path = path + File.separator;
    }
    if (new File(path).mkdir()) {
    System.out.println("创建目录:" + path + "成功!");
    return true;
    }
    return false;
    }