Search code examples
javaguavajava-io

Google guava: Using `ByteSource` and `ByteSink` after deprecation of `InputSupplier` and `OutputSupplier` utilities


I came across old code in my project which uses InputSupplier and OutputSupplier utility from Google Guava. Since these classes are deprecated in the latest version, I need to refactor my code accordingly.

By looking on the internet I came to know that I can use ByteSource and ByteSink in place of InputSupplier and OutputSupplier by doing some minimal changes. The below sample represents a case where I have used ByteSink in place of OutputSupplier.

  public static OutputSupplier<? extends OutputStream> newOutputSupplier() {
    return new OutputSupplier<OutputStream>() {
      @Override
      public OutputStream getOutput() throws IOException {
        return new FileOutputStream(file);         // file defined earlier
      }

After using ByteSink

public static ByteSink newOutputSupplier() {
    return new ByteSink() {
      @Override
      public OutputStream openStream() throws IOException {
        return new FileOutputStream(file); // file defined earlier
      }
    };
  }

Similar refactoring for InputSupplier related code.

Question 1: Is the above refactoring is correct? am I thinking in the right direction?

Question 2: Can i wrap ZipOutputStream in ByteSink ?

Question 3: If yes for the previous question, how will I get back the ZipOutputStream from ByteSink as it returns OutputStream? Will casting work in this case as in below snippet?

ZipOutputStream zipOutputStream = (ZipOutputStream) newOutputSupplier().openStream(); // Casting

Or do I need to create new ZipOutputStream from OutputStream?

ZipOutputStream zipOutputStream = new ZipOutputStream(newOutputSupplier().openStream());

Question 4: Can I wrap any kind of InputStream or OutputStream?

NOTE: I have mainly given example of OutputStream, ZipOutputStream and ByteSink but I am doing the similar things for InputStream, ZipInputStream and ByteSource.


Solution

    1. You should probably use e.g. Files.asByteSink.
    2. I wouldn't. ByteSink is intended for generic OutputStreams that don't have additional methods.
    3. Not applicable.
    4. Yes, as long as you can create a fresh one each time.