FileOutputStream进入FileInputStream

Pen*_*Pen 5 java file-io

将FileOutputStream转换为FileInputStream的最简单方法是什么(一段代码会很棒)?

Tho*_*mas 16

这可能对您有所帮助:

http://ostermiller.org/convert_java_outputstream_inputstream.html

本文提到了3种可能性:

  • 将完整输出写入字节数组然后再次读取
  • 用管子
  • 使用循环字节缓冲区(该页面上托管的库的一部分)


仅供参考,反过来做(输入到输出):

使用Apache Commons IO的简单解决方案是:

IOUtils.copyLarge(InputStream, OutputStream)
Run Code Online (Sandbox Code Playgroud)

或者如果您只想复制文件:

FileUtils.copyFile(inFile,outFile);
Run Code Online (Sandbox Code Playgroud)

如果您不想使用Apache Commons IO,请执行以下copyLarge方法:

public static long copyLarge(InputStream input, OutputStream output) throws IOException 
{
  byte[] buffer = new byte[4096];
  long count = 0L;
  int n = 0;
  while (-1 != (n = input.read(buffer))) {
   output.write(buffer, 0, n);
   count += n;
  }
  return count;
}
Run Code Online (Sandbox Code Playgroud)

  • 链接坏了,但你仍然可以在这里找到原来的答案:https://web.archive.org/web/20110929161214/http://ostermiller.org/convert_java_outputstream_inputstream.html (2认同)