Any way to create a URL from a byte array?

Is there any way to create a URL from a byte array? I have a custom class loader which stores all the entries from a JarInputStream in a HashMap storing the entry names with their bytes. The reason I'm looking to create a URL from a byte array is to satisfy the getResource(String name) method found in ClassLoaders. I've already accomplished getResourceAsStream(String name) by using a ByteArrayInputStream.


Assuming that you use a custom classloader and you want to store/cache the bytes of the content in a hashmap (not a location in byte[] form). Than you have the same question which brought me here. But this is how I was able to solve this:

class Somelassloader {
    private final Map<String, byte[]> entries = new HashMap<>();

    public URL getResource(String name) {

        try {
            return new URL(null, "bytes:///" + name, new BytesHandler());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

    }

    class BytesHandler extends URLStreamHandler {
        @Override
        protected URLConnection openConnection(URL u) throws IOException {
            return new ByteUrlConnection(u);
        }
    }

    class ByteUrlConnection extends URLConnection {
        public ByteUrlConnection(URL url) {
            super(url);
        }

        @Override
        public void connect() throws IOException {
        }

        @Override
        public InputStream getInputStream() throws IOException {
            System.out.println(this.getURL().getPath().substring(1));
            return new ByteArrayInputStream(entries.get(this.getURL().getPath().substring(1)));
        }
    }
}

java.net.URL doc: one of the constructors is URL(String spec) .

Then java.lang.String doc: one of the constructors is String(byte[] bytes) .

Create a String with your byte array and then use the created String to create the URL :

String urlString = new String(yourByteArray);
URL yourUrl = new URL(urlString);
链接地址: http://www.djcxy.com/p/58274.html

上一篇: Java适配器中的响应类型

下一篇: 任何方式从字节数组创建一个URL?