17

There are a few factory methods in Google Guava to create InputSuppliers, e.g. from a byte[]:

ByteStreams.newInputStreamSupplier(bytes);

Or from a File:

Files.newInputStreamSupplier(file);

Is there a similar way to to create an InputSupplier for a given InputStream?

That is, a way that's more concise than an anonymous class:

new InputSupplier<InputStream>() {
    public InputStream getInput() throws IOException {
        return inputStream;
    }
};

Background: I'd like to use InputStreams with e.g. Files.copy(...) or ByteStreams.equal(...).

4

3 回答 3

13

没有办法将任意InputStream转换为 an InputSupplier<InputStream>,因为 an应该是一个可以在每次调用其方法时InputSupplier<InputStream>创建一个全新的对象。这只有在底层的字节源可供重用时才有可能;因此工厂方法采用or并返回.InputStreamgetInput()byte[]FileInputSupplier<InputStream>

正如 Dimitris 所建议的,InputSupplier与 相关InputStream的方式与Iterable相关Iterator。您描述的匿名类是不正确的,因为每次调用它都会返回相同getInput()的流,因此后续调用将返回一个InputStream已经用尽并关闭的流。

这是您的匿名类的另一个问题:部分动机InputSupplier是限制实际的可见性,InputStream以便它可以自动关闭。如果您将外部可见包装InputStream在 an 中InputSupplier,然后将其传递给实用程序方法,则实用程序方法可能会关闭您的InputStream. 你可能会同意,但这不是 Guava 想要推广的干净的使用模式。

当我发现自己想做同样的事情时,我意识到我在做相反的事情。而不是这样做:

Files.copy(InputSupplier.of(inputStream), destinationFile);

(不存在),我应该这样做:

ByteStreams.copy(inputStream, Files.newOutputStreamSupplier(destinationFile));
于 2013-10-23T23:08:25.513 回答
10

不,我什么都没看到。
我想你已经找到了最好的方法。
将输入流存储在字节数组或文件中并使用 ByteStreams.newInputStreamSupplier() 或 Files.newInputStreamSupplier() 创建供应商的唯一替代方法,但我不鼓励这样做。
你也可以使用

public static long copy(InputStream from, OutputStream to)
ByteStreams
见:src

于 2010-03-02T13:56:13.253 回答
2

That would be as wrong as wrapping an Iterator to an Iterable, I feel there is like zero probability of such a thing going into the library. As elou says, you can use ByteStreams.copy() method, but there doesn't seem to be an obvious reason to do equals() on two streams.

I understand guava authors hesitation to add such a (trivial) method - how common can it be to fully (or partially, but without knowing where the stream was left, so it's as good as unusable thereafter) read two streams just to see if they are the same, without any other processing of the data? Do these bytes come from a non-repeatable-read source, like a network socket? Otherwise, if it is just a file somewhere, or an in-memory byte array, there are other ways that lend themselves to do an equality test.

于 2010-03-17T13:28:39.820 回答