0

One of my file and the current path is in

D:\project\major\sample\pp.txt

Let's say I have a file in major folder say lump.txt as (D:\project\major\lump.txt)

I don't know the folder name of major but knows the file name (lump.txt) as it is dynamic which gives the exact folder path of pp.txt alone. I want to move to the previous 1 folder, in this case, the major folder.

So I get the file object by

File file = new File("D:\\project\\major\\sample\\pp.txt")

Now I want to fetch the lump.txt file which is residing in the previous folder. But all of the below approaches doesn't fetch the file and always returns file doesn't exist

File file = new File(".\\sample\\lump.txt");
if(file.exists()) {
    Logger.info("file exist 1");
} else {
    Logger.info("file not exist 1");
}
file = new File(".\\.\\sample\\lump.txt");
if(file.exists()) {
    Logger.info("file exist 2");
} else {
    Logger.info("file not exist 2");
}
file = new File("..\\sample\\lump.txt");
if(file.exists()) {
    Logger.info("file exist 3");
} else {
    Logger.info("file not exist 3");
}
file = new File("...\\sample\\lump.txt");
if(file.exists()) {
    Logger.info("file exist 4");
} else {
    Logger.info("file not exist 4");
}

Please advise on how to resolve this problem. How to get the file?

Thanks

Abra
  • 19,142
  • 7
  • 29
  • 41
  • What is the current working directory when you start `java`? It should be `D:\project\major` as long I can see. – PeterMmm Mar 03 '22 at 12:01
  • [How to get just the parent directory name of a specific file](https://stackoverflow.com/a/8197136/1518100) – Lei Yang Mar 03 '22 at 12:10
  • I understand that you are trying to find the path to file `lump.txt`. Is that correct? – Abra Mar 03 '22 at 18:17

1 Answers1

0

Is this your requirement? Please check.

private static void fileParentDir() {
    File pp = new File("C:\\Users\\user\\Documents\\major\\sample\\pp.txt");

    if(pp != null && pp.isFile() && pp.exists()){
        System.out.println("Current folder : " + pp.getParent());
        System.out.println("Parent folder : " + pp.getParentFile().getParent());
        System.out.println("Lump exists : " + new File(pp.getParentFile().getParent(), "lump.txt").exists());
    }
}

Output

Current folder : C:\Users\user\Documents\major\sample
Parent folder : C:\Users\user\Documents\major
Lump exists : true
smilyface
  • 5,021
  • 8
  • 41
  • 57