Java isFile (), isDirectory () without checking for existence

I want to check if this String is a file or a directory, I tried the isFile () and isDirectory () File methods, but the problem is that if the directory or file does not exist, these methods return false, because, as stated in javadoc:

isFile () :

true if and only if there is a file indicated by this abstract path name and is a normal file; false otherwise

isDirectory () :

true if and only if there is a file indicated by this abstract path name and is a directory; false otherwise

Basically, I need two methods without an exist clause ...

So, I want to check whether a given line matches the directory format or matches the file format in a multi-platform context (therefore it should work on Windows, Linux and Mac Os X).

Is there any library that provides these methods? What could be the best implementation of these methods?

UPDATE

In the case of a line, which may be like (without extension) by default, it should be identified as a directory if a file with this path does not exist.

+6
source share
3 answers

It looks like you know what you want, according to your update: if the path does not exist, and the path has an extension, this is a file if it is not a directory. Something like this would be enough:

bool IsPathDirectory() { File test = new File(myPath); // check if the file/directory is already there if (!file.exists()) { // see if the file portion it doesn't have an extension return test.getName().lastIndexOf('.') == -1; } else { // see if the path that already in place is a file or directory return test.isDirectory(); } } 
+1
source

So, I want to check whether a given line matches the directory format or matches the file format in a multi-platform context (therefore it should work on Windows, Linux and Mac Os X).

On Windows, a directory may have an extension and does not require an extension. So you cannot tell just by looking at the line.

If you apply the rule that there is no extension in the directory, and the file always has the extension, then you can determine the difference between the directory and the file by looking for the extension.

+7
source

Why not just wrap them when calling File#exists() ?

 File file = new File(...); if (file.exists()) { // call isFile() or isDirectory() } 

That way, you are actually denying the β€œexists” part of isFile() and isDirectory() , since you are guaranteed to exist.


It is also possible that I misunderstood what you are asking here. Given the second part of your question, are you trying to use isFile() and isDirectory() for non-existent files to see if they look like files or directories?

If so, it will be difficult to do with the File API (and it is difficult to do at all). If /foo/bar/baz does not exist, it is not possible to determine if it is a file or directory. It could be.

+4
source

Source: https://habr.com/ru/post/904552/


All Articles