Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 642
user1625108 Avatar asked Jul 21 '13 21:07

user1625108


People also ask

How do you turn a URL into a byte?

URL u = new URL(content); openStream = u. openStream(); int contentLength = openStream. available(); byte[] binaryData = new byte[contentLength]; openStream.

How do you turn an object into a Bytearray?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

What is Bytearray?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

How do I print a Bytearray?

You can simply iterate the byte array and print the byte using System. out. println() method.


1 Answers

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 SomeClassLoader {
    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 {
            return new ByteArrayInputStream(entries.get(this.getURL().getPath().substring(1)));
        }
    }
}
like image 128
KIC Avatar answered Sep 19 '22 16:09

KIC