Why do we have to add forward slash in the file directory to differentiate between directory and files?

Viewed 316

Inside a for loop:

Why do I have to add a forward slash after the directory name? For example:

for(int i = 0; i<s.length; i++){
    File f = new File(dirname + "/" + s[i] ); 
    // Why to add "/" after dirname(i.e directory name)
    if(f.isDirectory()){
        System.out.println(s[i] + " is Directory" );
    }else{
        System.out.println(s[i] + " is File");
    }
}

If I remove backslash "/" after dirname:

File f = new File(dirname + "/" + s[i] ); 

When I remove "/":

File f = new File(dirname + s[i] ); 

It won't differentiate between directory and file. All the files inside will be considered to be the file. After I add a backslash, it will be okay. And it will differentiate between directory and file. Why is that? Why do I have to add "/". The program is meant to look inside the file without adding "/".

2 Answers

Including and omitting the / mean that the file points to a different path. For example, "foo/bar" and "foobar" are different paths, which would point to different objects in the file system:

Parent directory
+-- foobar     "foobar"
+-- foo
    +-- bar    "foo/bar"

Not being a directory is not the same thing as being a file. So, most likely (we don't know what's in your file system), it's not a directory because it doesn't exist.

You should check if (!f.exists()) (or similar) first:

if (!f.exists()) System.out.println("Doesn't exist");
else if (f.isDirectory()) ... etc

Also, note that you shouldn't add a / anyway - use the two-arg constructor:

File f = new File(dirname, s[i] ); 

Slash symbol is a file separator. This is used to separate the directories from the files.

If you are to build your string, the file name will be:

Pictures/my-dog.png

Here, you will see that there is a directory named "Picture" and a filename "my-dog.png".

If you were to remove the slash, it will look like a long filename:

Picturesmy-dog.png
Related