Java – Why do we put forward slashes in file directories to distinguish directories from files?

Why do we put forward slashes in file directories to distinguish directories from files?… here is a solution to the problem.

Why do we put forward slashes in file directories to distinguish directories from files?

In 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 the backslash “/”:: after dirname

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

When I remove “/”:

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

It does not distinguish between directories and files. All documents inside will be considered documents.
I’ll be fine after I add a backslash. It will distinguish between directories and files. Why is that?
Why do I add “/”. The program is designed to look inside the file without adding a “/”.

Solution

Include and omit / means that the file points to a different path. For example, “foo/bar” and “foobar" are different paths that will point to different objects in the file system:

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

Not a directory is different from 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 first check if (!f.exists()) (or similar):

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

Also, note that you shouldn’t add / – using the two-parameter constructor :, anyway

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

Related Problems and Solutions