2

I'm working with the File class for the first time and am a little confused.

I wrote this basic code to see if a file on my desktop could be detected:

public static void main(String[]args){
    File test= new File("abc.pdf");
    if(test.exists()==true){
        System.out.println("got it!");
    }
    else{System.out.println("try again");}
}

I know I'm missing a big step since the program can't seem to detect it. Can anyone tell me what else I need to look up? Thanks.

user2910237
  • 133
  • 1
  • 2
  • 7

2 Answers2

6

You need to specify absolute path. e.g:

File file = new File("C:\\abcfolder\\abc.pdf");

In order to get the desktop absolute path:

String desktopPath = WindowsUtils.getCurrentUserDesktopPath();

Then:

File file = new File(desktopPath+"\\abc.pdf");
Community
  • 1
  • 1
aviad
  • 8,229
  • 9
  • 50
  • 98
  • great it works. thanks!...and if i wanted to check for a file but didn't necessarily know the location of it, do you by any chance know of some sort of search method built into the java library? – user2910237 Mar 16 '14 at 08:18
  • @user2910237 You can take a look at DirectoryWalker in commons.io : http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/DirectoryWalker.html It enables you to walk through the file hierarchy, and do something with specified files. Btw. if you learn IO in Java it a perfect moment to take a look at commons.io - extremely helpful stuff ;) – radekEm Mar 16 '14 at 08:23
3

If you're running this in Eclipse, it will look for the file in the project folder.

If you're running this from a command line, it will look in the current folder.

If you're running this from a jar file, it will look in the folder with the jar file, at least on Windows.

If you're running this somewhere else, it depends on how you're running it. In most IDEs it will be the project folder.

user253751
  • 57,427
  • 7
  • 48
  • 90