31

私は、InputStream を OutputStream にパイプする最良の方法を見つけようとしていました。Apache IO のような他のライブラリを使用するオプションはありません。これがスニペットと出力です。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class Pipe {
    public static void main(String[] args) throws Exception {

        for(PipeTestCase testCase : testCases) {
            System.out.println(testCase.getApproach());
            InputStream is = new FileInputStream("D:\\in\\lft_.txt");
            OutputStream os = new FileOutputStream("D:\\in\\out.txt");

            long start = System.currentTimeMillis();            
            testCase.pipe(is, os);
            long end = System.currentTimeMillis();

            System.out.println("Execution Time = " + (end - start) + " millis");
            System.out.println("============================================");

            is.close();
            os.close();
        }

    }

    private static PipeTestCase[] testCases = {

        new PipeTestCase("Fixed Buffer Read") {         
            @Override
            public void pipe(InputStream is, OutputStream os) throws IOException {
                byte[] buffer = new byte[1024];
                while(is.read(buffer) > -1) {
                    os.write(buffer);   
                }
            }
        },

        new PipeTestCase("dynamic Buffer Read") {           
            @Override
            public void pipe(InputStream is, OutputStream os) throws IOException {
                byte[] buffer = new byte[is.available()];
                while(is.read(buffer) > -1) {
                    os.write(buffer);   
                    buffer = new byte[is.available() + 1];
                }
            }
        },

        new PipeTestCase("Byte Read") {         
            @Override
            public void pipe(InputStream is, OutputStream os) throws IOException {
                int c; 
                while((c = is.read()) > -1) {
                    os.write(c);    
                }
            }
        }, 

        new PipeTestCase("NIO Read") {          
            @Override
            public void pipe(InputStream is, OutputStream os) throws IOException {
                FileChannel source      = ((FileInputStream) is).getChannel(); 
                FileChannel destnation  = ((FileOutputStream) os).getChannel();
                destnation.transferFrom(source, 0, source.size());
            }
        }, 

    };
}


abstract class PipeTestCase {
    private String approach; 
    public PipeTestCase( final String approach) {
        this.approach = approach;           
    }

    public String getApproach() {
        return approach;
    }

    public abstract void pipe(InputStream is, OutputStream os) throws IOException;
}

出力 (~4MB 入力ファイル) :

Fixed Buffer Read
Execution Time = 71 millis
============================================
dynamic Buffer Read
Execution Time = 167 millis
============================================
Byte Read
Execution Time = 29124 millis
============================================
NIO Read
Execution Time = 125 millis
============================================

「動的バッファー読み取り」はavailable()メソッドを使用します。しかし、Java docs によると信頼性がありません

このメソッドの戻り値を使用して、このストリーム内のすべてのデータを保持するためのバッファーを割り当てることは決して正しくありません。

「Byte Read」は非常に遅いようです。

「固定バッファ読み取り」はパイプに最適なオプションですか? 何かご意見は?

4

4 に答える 4

14

私はこれに出くわしましたが、最後の読み取りで問題が発生する可能性があります。

推奨される変更:

public void pipe(InputStream is, OutputStream os) throws IOException {
  int n;
  byte[] buffer = new byte[1024];
  while((n = is.read(buffer)) > -1) {
    os.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
  }
 os.close ();

また、1024 よりも 16384 の方がおそらく固定バッファー サイズとして優れていることにも同意します。

私見では...

于 2013-01-31T20:50:39.310 に答える
12

固定バッファ サイズが最適/最も理解しやすいと言えます。ただし、いくつかの問題があります。

  • 毎回バッファ全体を出力ストリームに書き込んでいます。最後のブロックでは、読み取りが 1024 バイト未満である可能性があるため、書き込みを行うときにこれを考慮する必要があります (基本的には、によって返されたバイト数のみを書き込みます)。 read()

  • 動的バッファーの場合は、 を使用しますavailable()。これは、それほど信頼できる API 呼び出しではありません。この場合、ループ内で問題ないかどうかはわかりませんが、InputStream の一部の実装で最適に実装されていなくても驚かないでしょう。

  • キャスト先の最後のケースFileInputStream。これを汎用にする場合は、このアプローチを使用できません。

于 2012-07-30T06:00:13.240 に答える