[java] Java InputStream의 내용을 OutputStream에 작성하는 쉬운 방법

나는 내가의 내용을 쓸 수있는 간단한 방법을 추적 할 수 없다는 것을 오늘 발견 놀랐습니다 InputStreamOutputStream자바를. 분명히 바이트 버퍼 코드를 작성하는 것은 어렵지 않지만 인생을 더 쉽게 (그리고 코드를 더 명확하게) 만들 수있는 것이 빠져 있다고 생각합니다.

따라서 InputStream inand가 주어지면 OutputStream out다음을 작성하는 더 간단한 방법이 있습니까?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}



답변

자바 9

Java 9부터 다음 서명으로 InputStream호출되는 메소드를 제공합니다 transferTo.

public long transferTo(OutputStream out) throws IOException

현상태대로 문서의 상태, transferTo것입니다 :

이 입력 스트림로부터 모든 바이트를 읽고, 읽은 순서대로 지정된 출력 스트림에 바이트를 기입합니다. 돌아 왔을 때,이 입력 스트림은 스트림의 말미에 있습니다. 이 방법은 스트림을 닫지 않습니다.

이 방법은 입력 스트림에서 무한히 읽거나 출력 스트림에 쓰는 것을 차단할 수 있습니다. 입력 및 / 또는 출력 스트림이 비동기식으로 닫히거나 전송 중에 스레드가 중단 된 경우의 동작은 입력 및 출력 스트림에 따라 달라 지므로 지정되지 않습니다.

그래서 자바의 내용을 쓰기 위해 InputStream에를 OutputStream, 당신은 쓸 수 있습니다 :

input.transferTo(output);


답변

WMR에서 언급했듯이 org.apache.commons.io.IOUtilsApache에는 copy(InputStream,OutputStream)원하는 것을 정확하게 수행 하는 메소드 가 있습니다.

따라서, 당신은 :

InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();

… 당신의 코드에서.

피해야 할 이유가 IOUtils있습니까?


답변

Java 7을 사용하는 경우 파일 (표준 라이브러리)이 가장 좋은 방법입니다.

/* You can get Path from file also: file.toPath() */
Files.copy(InputStream in, Path target)
Files.copy(Path source, OutputStream out)

편집 : 물론 파일에서 InputStream 또는 OutputStream 중 하나를 만들 때 유용합니다. file.toPath()파일에서 경로를 얻는 데 사용 합니다.

기존 파일 (예 :로 만든 파일)에 쓰려면 복사 옵션 File.createTempFile()을 전달해야합니다 REPLACE_EXISTING(그렇지 않으면 FileAlreadyExistsExceptionthrow 됨).

Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)


답변

나는 이것이 효과가 있다고 생각하지만 그것을 테스트해야합니다 … 사소한 “개선”이지만 가독성에 약간의 비용이들 수 있습니다.

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}


답변

구아바 사용 ByteStreams.copy():

ByteStreams.copy(inputStream, outputStream);


답변

간단한 기능

당신이 단지를 작성이 필요하면 InputStreamA와 File당신은이 간단한 기능을 사용할 수 있습니다 :

private void copyInputStreamToFile( InputStream in, File file ) {
    try {
        OutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


답변

JDK(아마 어떤 다른 어쨌든하지 않음) 어설픈 타사 라이브러리 없이는 “쉬운”방법이없는 것처럼 사용하는 동일한 코드 보인다 있도록. 다음에서 직접 복사됩니다 java.nio.file.Files.java.

// buffer size used for reading and writing
private static final int BUFFER_SIZE = 8192;

/**
  * Reads all bytes from an input stream and writes them to an output stream.
  */
private static long copy(InputStream source, OutputStream sink) throws IOException {
    long nread = 0L;
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while ((n = source.read(buf)) > 0) {
        sink.write(buf, 0, n);
        nread += n;
    }
    return nread;
}