开发者

Single inputstream containing two files. I want to split those files

开发者 https://www.devze.com 2023-02-16 13:37 出处:网络
In java I\'m having an inputstream (maybe 开发者_如何转开发sequenceinputstream) containing more than one file. I want to separate those files using java. Is there any solution available in java? The s

In java I'm having an inputstream (maybe 开发者_如何转开发sequenceinputstream) containing more than one file. I want to separate those files using java. Is there any solution available in java?


The simple answer is: you can't / shouldn't.

The complicated answer: in case you are dealing with a SequenceInputStream, you can access the underlying streams using this reflection hack:

@SuppressWarnings("unchecked")
public static Enumeration<InputStream> split(final SequenceInputStream sis){
    try{
        Field streamsEnumField =
            SequenceInputStream.class.getDeclaredField("e");
        streamsEnumField.setAccessible(true);
        return (Enumeration<InputStream>) streamsEnumField.get(sis);
    } catch(final Exception e){
        throw new IllegalStateException(e);
    }
}

But I would be very careful about using something like this.


This depends on what kind of files you have, if there is any reserved squence which indicates the End and/or the beginning of the file like HTML or XML etc. then you can separate them, otherwise i don't see any way to do this.


You need to have some way of determining where one file ends and the next begins- most files reserve the first few bytes as an "identity" tag. Bear in mind that Java's insistence on having a SIGNED byte class can mess with identifying these at runtime.

However, you can't really split streams. So, you'll have to stage your data through ordinary byte[] arrays. I'd read from the parent stream in chunks of 4K (for files) or 64K (for the network) since the underlying native calls usually use those sizes, store the chunks in lists, and then create a ByteArrayInputStream for each file at the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消