Checking to see if a file exists in java
Attention reader! Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. Next Java. File Class in Java. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. We have seen that File. To explicitly avoid checking for a directory, it is recommended to use File. The File. From Java 7 onward, we can use java. Files , which provides several static methods that operate on files, directories, or other types of files.
Files class. The exists method returns true if the file exists, whereas the notExists method returns true when it does not exist. If both exists and notExists return false, the existence of the file cannot be verified. This can happen when the program does not have access to the file. Note that Files. Ask Question.
Asked 3 years, 11 months ago. Active 3 years, 11 months ago. Viewed times. Daniel Flower. Daniel Flower Daniel Flower 7 7 silver badges 12 12 bronze badges. Why would an existence check or getting a file's size require opening the file? You can write a thread that monitors changes in a directory and access the data maintained by it if even a directory read isn't tolerable.
Why isn't? There isn't, in general, even a way to do this from lower-level languages although it's OS dependent of course.
So, no, there's no way to do it from Java other than spawning a separate dedicated thread. It appears to be blocking or it is blocking? Why use File path. Files exists Path, LinkOptions here? You can check what is the OS and use appropriate command error or resort to directory stream if not supported. If you wish simplicity and don't need to report a progress, you can avoid dealing with the process IO and store the list to a temporary file e.
Alternatively, you can read from the process output directly. Read with a buffered stream, a reader or alike, with large enough buffer. On SSD it will complete in a blink of an eye and on modern HDD in seconds half million files is not a problem with this approach. Once you have the list, you can approach it differently depending on maximum files count and memory requirements.
If requirements are loose, e. Shortening path by removing common root will require much less memory. You can also reduce memory by keeping only filename hash instead of full name common root removal will probably reduce more.
Or you can optimize it further if you wish, the question just reduces now to a problem of checking existense of a string in a list of strings stored in memory or file, which has many well known optimal solutions.
Bellow is very loose, simplistic sample for Windows. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams?
0コメント