开发者

Java - Strange directory problem?

When I run a class with the following code:

public static void main(String[] args)
{
    createDuplicateStructure("in", "out");
}

public static void createDuplicateStructure(String path_start, String path_result)
{
    File start = new File(path_start);
    File result = new File(path_result);
    duplicateDirectoryStructure(start, result);
}

public static void duplicateDirectoryStructure(File start_dir, File res开发者_开发百科ult_dir)
{
    //FileFilter used by listFiles(filter) - to make sure they are dirs
    FileFilter dirs_only = new FileFilter() 
            { 
                public boolean accept(File file){  return file.isDirectory();} 
            };
    File[] dir_contents = start_dir.listFiles(dirs_only);
    for(File dir : dir_contents)
    {
        File duplicate = new File(result_dir.getPath(), dir.getName());
        if(dir.mkdir())
        {
            duplicateDirectoryStructure(dir, duplicate);
        }
        else
        {
            System.out.println("ERROR: Unable to create dir! (" + duplicate.getPath() + ")");
        }
    }
}

I get this in the console:

 Error: Unable to create dir! (out/a)
 Error: Unable to create dir! (out/a)
 Error: Unable to create dir! (out/a)

The directory "out" is in the same directory as the .jar. There is a directory "in" which contains "a", "b", and "c" directories (for testing).

Any ideas why this is not working?

Thanks!


You should replace dir.mkdir() with duplicate.mkdir() because dir is the already existing source directory.


dir.mkdir() only returns true the directory was actually created. Try doing

if(dir.mkdir() || dir.exists())


The line

`if(dir.mkdir())`

is trying to create the existing directory structure

if you change it to
if(duplicate.mkdir())

you get another problem where it tries to create the a subdirectory under out which does not exist yet.

So change it to
if(duplicate.mkdirs())

which will create the directory structure, or create the out directory before you start your loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜