Mike
Mike

Reputation: 779

can't access a file directory

This might be really nooby, but I'm trying to access a file directory so I can load all the images in it. For some reason when I input a file directory such as "/Images" it comes out as "\Images" when I create a new file and Windows can't find the directory because it's a backslash...

Code:

private final String imgDir =  "/Images";

File dir = new File(imgDir);

System.out.println(imgDir);
System.out.println(dir);

File[] files = dir.listFiles(new FilenameFilter() {
  public boolean accept(File dir, String fname) {
     return fname.endsWith(".png") || fname.endsWith(".bmp") || fname.endsWith(".jpg");
  }
});

the print outputs are "/Images" and "\Images" respectively. files always comes out null because the dir is wrong. Any ideas why this could be?

EDIT: Ok I got it to work. You guys were all right that I needed to used a relative path, but since it was IN the src folder I just needed to make it ".\src\Images" :D Is it bad practice to do this? Should I just move the Images folder to the root project directory?

Upvotes: 0

Views: 153

Answers (2)

user207421
user207421

Reputation: 310883

Windows can't find the directory because it's a backslash

That's not the reason. Windows uses backslash itself.

files always comes out null because the dir is wrong.

That would do it, for example if as per your comments you meant ./Images but you actually coded /Images.

Upvotes: 0

Turix
Turix

Reputation: 4490

Try composing your string using File.separator instead of explicit slashes, for example: private final String imgDir = File.separator + "Images".

Upvotes: 2

Related Questions