0

I am beginner at java and I want to check if the string path that the user provide for the file is valid or not, e.g if the path exists, if contains is not null and the file is not empty and etc. How can I do that?

private static final String FILE_PATH = "com.var.file.path";
String file_path = System.getProperty(FILE_PATH, DEFAULT_FILE_PATH);
user3409650
  • 505
  • 3
  • 12
  • 25
  • 5
    ... `new File(file_path).exists()`?! – Trinimon Oct 10 '14 at 09:55
  • Which version of Java are you using? If 7+ You could also use [`Files.exists(Paths.get(file_path))`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#exists(java.nio.file.Path,%20java.nio.file.LinkOption...)) – Edd Oct 10 '14 at 10:46
  • and when the file does not exist how can I log the error message via logger? the code stuck after when the file does not exist – user3409650 Oct 10 '14 at 10:56
  • Are you using `java.util.logging`? – user1803551 Oct 10 '14 at 12:38
  • yes I use that and I slo need to close the file but do not know where to do that inside try and catch – user3409650 Oct 10 '14 at 13:28

1 Answers1

1

There is a boolean built in to the File class that will check it for you.

Do:

if(new File(file_path).exists())
{
    //Do Stuff
}else{
    System.err.println("Error: " + file_path + " does not exist.");
    //Or whatever other output stream you want to use
}
EKW
  • 2,059
  • 14
  • 24