栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

是否可以创建指向内存中对象的URL?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

是否可以创建指向内存中对象的URL?

也许有点晚了(4年后),但是对于其他正在寻找类似解决方案的人,您可以使用我创建的URL工厂:

public class InMemoryURLFactory {    public static void main(String... args) throws Exception {        URL url = InMemoryURLFactory.getInstance().build("/this/is/a/test.txt", "This is a test!");        byte[] data = IOUtils.toByteArray(url.openConnection().getInputStream());        // Prints out: This is a test!        System.out.println(new String(data));    }    private final Map<URL, byte[]> contents = new WeakHashMap<>();    private final URLStreamHandler handler = new InMemoryStreamHandler();    private static InMemoryURLFactory instance = null;    public static synchronized InMemoryURLFactory getInstance() {        if(instance == null) instance = new InMemoryURLFactory();        return instance;    }    private InMemoryURLFactory() {    }    public URL build(String path, String data) {        try { return build(path, data.getBytes("UTF-8"));        } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex);        }    }    public URL build(String path, byte[] data) {        try { URL url = new URL("memory", "", -1, path, handler); contents.put(url, data); return url;        } catch (MalformedURLException ex) { throw new RuntimeException(ex);        }    }    private class InMemoryStreamHandler extends URLStreamHandler {        @Override        protected URLConnection openConnection(URL u) throws IOException { if(!u.getProtocol().equals("memory")) {     throw new IOException("Cannot handle protocol: " + u.getProtocol()); } return new URLConnection(u) {     private byte[] data = null;     @Override     public void connect() throws IOException {         initDataIfNeeded();         checkDataAvailability();         // Protected field from superclass         connected = true;     }     @Override     public long getContentLengthLong() {         initDataIfNeeded();         if(data == null)  return 0;         return data.length;     }     @Override     public InputStream getInputStream() throws IOException {         initDataIfNeeded();         checkDataAvailability();         return new ByteArrayInputStream(data);     }     private void initDataIfNeeded() {         if(data == null)  data = contents.get(u);     }     private void checkDataAvailability() throws IOException {         if(data == null)  throw new IOException("In-memory data cannot be found for: " + u.getPath());     } };        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496333.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号