0

In Java using Maven project we may read file's content as a stream by knowing only file's name, for example:

InputStream in = getClass().getResourceAsStream("/" + fileName);

But is there way to check if the file exists without indicating the whole path, just passing file name?

  • 1
    File f = new File(fileName); if (f.exists()) ... that should do the trick – Stultuske Jan 22 '20 at 11:19
  • 1
    Does this answer your question? [How do I check if a file exists in Java?](https://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java) – Sudhir Ojha Jan 22 '20 at 11:23
  • 2
    A resource is not necessarily a file? And the above will return null if your resource does not exist (which is the check for a resource existing) – pandaadb Jan 22 '20 at 11:31
  • 1
    The problem is your terminology. You are erroneously calling a resource a "file". The Java definition of a file is something that resides in a filesystem A resource does not: it typically resides in a jar as a zip entry. By asking about files, you are getting the wrong answers. – DodgyCodeException Jan 22 '20 at 11:37

1 Answers1

0

file.exists() can be used to check whether such a file exists or not.Like following:

File file = new File("filepath"); 
if(file.exists()){
   // Do your stuff
}
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
Pandit Biradar
  • 1,777
  • 3
  • 20
  • 35
  • the main point here is to avoid filepath, just knowing the name of the file – flintEastvood Jan 22 '20 at 11:28
  • @flintEastvood without knowing where the file is, you can't check anything ... obvious. You can check that A file exists with said name. just do a recursive search over all your directories and check in each if the file is there. – Stultuske Jan 22 '20 at 11:31