Any way to create a url from an array of bytes?

Is there a way to create a url from an array of bytes? I have a custom class loader that stores all the entries from the JarInputStream in the HashMap, storing the names of the entries with their bytes. The reason I'm trying to create a URL from an array of bytes is to satisfy the getResource (String name) method found in ClassLoaders. I already executed getResourceAsStream (string name) using ByteArrayInputStream.

+4
source share
2 answers

Assuming you are using a custom classloader and you want to store / cache bytes of content in a hash map (and not in form in byte []). Then you have the same question that brought me here. But that’s 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))); } } } 
+4
source

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

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

Create a String using the byte array, and then create a String to create the URL :

 String urlString = new String(yourByteArray); URL yourUrl = new URL(urlString); 
-one
source

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


All Articles