开发者

How do I refer to a directory in Java?

I'm running Windows and I'm trying to refer to a directory. My function starts off like this:

File file = new File("C:\\somedir\\report");
if (!file.exists(开发者_StackOverflow社区)) {
  file.mkdirs();
}
doStuffWith(file);

I got a NullPointerException within the doStuffWith function, when I tried to call listFiles. Well I looked in C:\somedir and what did I find - there is a file called "report" with no extension, and also a directory called "report"! What seemed to happen was that the file object was referring to the report file rather than the directory. How do I make sure that I am referring to the directory and not the file?


one way to go about is to pass the file object corresponding to "C:\somedir" to the method and inside the method, do a listFiles() and walk through the contents, each time checking for file name and if it is "report", do a isDirectory(). proceed with actual processing when this returns true.


i think there is a isDirectory() method that will tell you if it is a directory

--EDIt

that's what I get for being up so early. I ran your code locally and it works fine for me. Was able to create new files, read directory contents, etc. What else are you trying to do?


I don't understand the problem this works fine for me:

public class MkDir {
    static void doStuff(File dir) {
        if ( dir.isDirectory() ) {
            File[] listFiles = dir.listFiles();
            for ( File f : listFiles ) {
                System.out.println( f.getName() );
            }
        }
    }

    public static void main(String[] args) {
        File file = new File( "C:\\dev\\rep2\\rep" );
        if ( !file.exists() ) {
            file.mkdirs();
        }
        doStuff( file );
    }
}


Check if your file system has had case sensitivity enabled (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\kernel\ dword:ObCaseInsensitive in the registry.)

If so, you may be getting bitten by a case-related issue. One way to check:

String someName = "./nameNotUsedYet";
boolean first = new File(someName).mkdirs();
boolean second = new File(someName.toUpperCase()).mkdirs();
System.out.println("first = " + first + ", second = " + second);

If both mkdirs() calls succeeded, you know you have a case related complication. If so, ensure that you get the case for "C:\somedir\report" exactly right.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜