0

Like the title says, I need to find the directory/path of a file. I know that the computer running the program has the file but I don't know the path/directory. The only thing I know about the file is its name(file.jar).

File f = new File("file.jar");
    String ap = f.getAbsolutePath();
    return ap;

I have already tried using getAbsolutePath() method and it didn't work so I was wondering if there was another way to get the directory/path of file.jar.

  • Did you try this: http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/ ? –  Jul 17 '14 at 15:42
  • Try file.getParent() (or file.getParentFile()) – clever_bassi Jul 17 '14 at 15:42
  • possible duplicate of [How do I get a file's directory using the File object?](http://stackoverflow.com/questions/3657157/how-do-i-get-a-files-directory-using-the-file-object) – clever_bassi Jul 17 '14 at 15:45
  • @ayushi .getParent() and getParentFile() just return null when I use them. – user3726628 Jul 17 '14 at 15:54
  • File f = new File("test/../file.jar") Give the absolute path. – clever_bassi Jul 17 '14 at 16:01
  • 1
    @ayushi That's a relative path, and OP can't give the absolute path, or the relative path, because s/he doesn't know it. – David Conrad Jul 17 '14 at 16:19
  • Oh sorry I meant give the absolute path as in something like this: D:/test1/test.txt. Thanks for correcting me – clever_bassi Jul 17 '14 at 16:24
  • What do you mean by "it didn't work"? What did it return? What were you expecting? – Andrew Stubbs Jul 18 '14 at 07:19
  • @AndrewStubbs It returned directories that didn't exist because(as said in the answer i got) it was trying to open a file in my working directory. I expected it to give me the directory of file.jar but it gave me the directory of file.jar where it was trying to open it(my working directory) and file.jar wasn't in my working directory. – user3726628 Jul 18 '14 at 21:55

1 Answers1

2

The argument given to the File-constructor is a path relative to the working directory (as long as you don't pass an absolute path). The constructor won't search for this file but just tries to open a file with that name in your working directory.

This might help if you want to search for files: http://docs.oracle.com/javase/tutorial/essential/io/find.html

wolff
  • 426
  • 4
  • 11