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.
URL u = new URL(content); openStream = u. openStream(); int contentLength = openStream. available(); byte[] binaryData = new byte[contentLength]; openStream.
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.
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..
You can simply iterate the byte array and print the byte using System. out. println() method.
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)));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With