Ever needed an URL that reads its bytes from memory?
This may be useful when you need to redirect a stream through some filter.
Here is a Java class that does this stunningly simple.
Mind that it is for a small amount of data only,
all bytes (String data
) must be in memory for this to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.Objects; public final class InMemoryUrl { public static URL build(String data) { Objects.requireNonNull(data); try { return URL.of( new URI("InMemory", "DummyPath", null), // protocol, path, reference new InMemoryUrlStreamHandler(data.getBytes())); } catch (Exception e) { throw new RuntimeException(e); } } private static class InMemoryUrlStreamHandler extends URLStreamHandler { private final byte[] data; public InMemoryUrlStreamHandler(byte[] data) { this.data = data; } @Override protected URLConnection openConnection(URL url) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { connected = true; } @Override public long getContentLengthLong() { return data.length; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } }; } } private InMemoryUrl() {} } |
Here is a test main that you can use to try it out:
public static void main(String[] args) throws Exception { final URL url = InMemoryUrl.build("This is a test with non-ASCII chars: ÄÜÖ äüö ß"); final byte[] data = url.openConnection().getInputStream().readAllBytes(); System.out.println(new String(data)); }