Detecting directories opened by java.lang.Class.getResourceAsStream ()

Assuming the following resources are in the class path:

/res/image/logo.png
/res/image/splash.png

Then you can get InputStreamfor logo.png using:

SomeClass.class.getResourceAsStream("/res/image/logo.png");

If you request a resource that does not exist, getResourceAsStream()returns null.

However, if you request a resource that is truly a directory, you will not get null or exception: you really get java.io.ByteArrayInputStream. By dropping bytes from this stream, it appears to be a list of resources in this directory (one per line).

So:

SomeClass.class.getResourceAsStream("/res/image");

Gives a ByteArrayInputStream, which when dropped contains:

logo.png
splash.png

, , getResourceAsStream(), ? - , , ? ( getResource() - , ?)

UPDATE:

getResource() URL- "", , , ( /java/util/List.class). :

jar:file:/C:/projects/<my_proj>/env/jdk/jre/lib/rt.jar!/java/util/List.class

/java/util :

null

, null ( , , , ) , "" , URL- "file:". , File.isDirectory(), .

, . , !; -)

+4
5

getResource() URL-. URL, "file://", new File(name).isDirectory().

"file://", -, , .

"/". "/.." URL- - , URL- .

+1

getResource() getResource() , , : , path "/" ( ).

, . URL file: :

URL url = Foo.class.getResource(".");
if(url.getProtocol().equals("file"))
{
  boolean dir=new File(url.toURI()).isDirectory();
}

. ( ). JAR null, JAR .

+1

, getResourceAsStream , , , URL- getResource, new File(path).isDirectory() new File(path).isFile()

0

:

URL resource = getClass().getResource("/res/image");
File folder = new File(new URI(resource.getPath()).getPath());
if(folder.isDirectory()) {
    // do something
}
0

You can determine if a InputStreamfile or directory is a class. If it is a file, it will be "BufferedInputStream" and the directory will be "ByteArrayInputStream".

public boolean isDirectory(InputStream is) {
  return is.getClass().getSimpleName().equals("ByteArrayInputStream");
}

public boolean isFile(InputStream is) {
  return is.getClass().getSimpleName().equals("BufferedInputStream");
}

For example:

InputStream is = SomeClass.class.getResourceAsStream("/res/image");
boolean isDirectory = isDirectory(is); //true
0
source

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


All Articles