5

有没有办法从字节数组创建 URL?我有一个自定义类加载器,它将 JarInputStream 中的所有条目存储在 HashMap 中,存储条目名称及其字节。我希望从字节数组创建 URL 的原因是满足 ClassLoaders 中的 getResource(String name) 方法。我已经使用 ByteArrayInputStream 完成了 getResourceAsStream(String name)。

4

2 回答 2

6

假设您使用自定义类加载器,并且您希望将内容的字节存储/缓存在哈希图中(而不是 byte[] 形式的位置)。比你有同样的问题把我带到这里。但这就是我能够解决这个问题的方法:

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)));
        }
    }
}
于 2015-11-13T08:26:04.257 回答
-1

java.net.URL doc:构造函数之一是URL(String spec).

然后java.lang.String doc : 构造函数之一是String(byte[] bytes).

String使用您的数组创建一个,byte然后使用创建String的创建URL

String urlString = new String(yourByteArray);
URL yourUrl = new URL(urlString);
于 2013-07-22T07:34:03.980 回答