1

On Linux:

File: /home/user/somedir/myfile.txt
Dir:  /home/user/

(result true)

On Windows:

File: C:\SomeDir1\Dir2\Dir3\myfile.txt
Dir:  C:\SomeDir1

(result true)

File: C:\SomeDir1\Dir2\Dir3\myfile.txt
Dir:  C:\SomeDir2\Dir3

(result false)

So, I need to make sure if a specified file has a parent directory

I have an idea to implement it by converting to String and comparing it by characters, but in this case I need to replace all \ to / and add / in the end of directory if it's not here, I'm not sure if it's the best way, but not code monkey. Please advise

Phantomazi
  • 408
  • 6
  • 22
bagi
  • 21
  • 2
  • 8

3 Answers3

2

This should do the trick:

boolean hasParent = new File("path/to/file").getParentFile() != null;
epoch
  • 16,396
  • 4
  • 43
  • 71
Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29
2

Assuming you are using Java >= 7, you can check if a Path has a parent with the method Path.getParent(). This method returns null if the path does not have a parent.

Path path = Paths.get("/home/user/somedir/myfile.txt");
boolean hasParent = path.getParent() != null;

Note that this method handles the path separator correctly, dependending on the platform, so you don't need to worry about it.

However, as noted in the Javadoc, this does not check that the given Path actually exists on the filesystem. You might want to add a check for that using Files.exists(path).

Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

Use getParentFile(). It Returns the parent directory as a File object, or null if this File object does not have a parent.

E.g :

import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File myFile = new File("C:" + File.separator + "jdk1.5.0" + File.separator, "File.java");
    System.out.println(myFile.getParentFile());
    System.out.println(myFile);
  }
}

Output -

C:\jdk1.5.0

C:\jdk1.5.0\File.java

Snehal Masne
  • 3,403
  • 3
  • 31
  • 51