Java - Escreva um InputStream em um arquivo

Java - Escreva um InputStream em um arquivo

1. Visão geral

Neste tutorial rápido, vamos ilustrar comowrite an InputStream to a File - primeiro usando Java simples, depois Guava e finalmente a biblioteca Apache Commons IO.

Este artigo faz parte dethe “Java – Back to Basic” tutorial aqui no exemplo.

Leitura adicional:

Java - InputStream para o Reader

Como converter um InputStream em um Reader usando Java, Guava e a biblioteca Apache Commons IO.

Read more

Java - Converter arquivo para InputStream

Como abrir um InputStream a partir de um arquivo Java - usando Java simples, Guava e a biblioteca Apache Commons IO.

Read more

Java InputStream para Byte Array e ByteBuffer

Como converter um InputStream em um byte [] usando Java, Guava ou Commons IO simples.

Read more

2. Converter usando Java simples

Vamos começar comthe Java solution:

@Test
public void whenConvertingToFile_thenCorrect()
  throws IOException {

    InputStream initialStream = new FileInputStream(
      new File("src/main/resources/sample.txt"));
    byte[] buffer = new byte[initialStream.available()];
    initialStream.read(buffer);

    File targetFile = new File("src/main/resources/targetFile.tmp");
    OutputStream outStream = new FileOutputStream(targetFile);
    outStream.write(buffer);
}

Observe que, neste exemplo, o fluxo de entrada possui dados conhecidos e pré-determinados - como um arquivo em disco ou um fluxo na memória. Por causa disso,we don’t need to do any bounds checkinge podemos - se a memória permitir - simplesmente ler e escrever de uma vez.

Java - Write an Input Stream to a File

 

Se o fluxo de entrada estiver vinculado a umongoing stream of data - por exemplo, uma resposta HTTP proveniente de uma conexão em andamento - ler o fluxo inteiro uma vez não é uma opção. Nesse caso, precisamos nos certificar de quekeep reading until we reach the end of the stream:

@Test
public void whenConvertingInProgressToFile_thenCorrect()
  throws IOException {

    InputStream initialStream = new FileInputStream(
      new File("src/main/resources/sample.txt"));
    File targetFile = new File("src/main/resources/targetFile.tmp");
    OutputStream outStream = new FileOutputStream(targetFile);

    byte[] buffer = new byte[8 * 1024];
    int bytesRead;
    while ((bytesRead = initialStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }
    IOUtils.closeQuietly(initialStream);
    IOUtils.closeQuietly(outStream);
}

Finalmente, aqui está outra maneira simples de usar o Java 8 para fazer a mesma operação:

@Test
public void whenConvertingAnInProgressInputStreamToFile_thenCorrect2()
  throws IOException {

    InputStream initialStream = new FileInputStream(
      new File("src/main/resources/sample.txt"));
    File targetFile = new File("src/main/resources/targetFile.tmp");

    java.nio.file.Files.copy(
      initialStream,
      targetFile.toPath(),
      StandardCopyOption.REPLACE_EXISTING);

    IOUtils.closeQuietly(initialStream);
}

3. Converter usando Guava

A seguir - vamos dar uma olhada em uma solução mais simples baseada em Guava:

@Test
public void whenConvertingInputStreamToFile_thenCorrect3()
  throws IOException {

    InputStream initialStream = new FileInputStream(
      new File("src/main/resources/sample.txt"));
    byte[] buffer = new byte[initialStream.available()];
    initialStream.read(buffer);

    File targetFile = new File("src/main/resources/targetFile.tmp");
    Files.write(buffer, targetFile);
}

4. Converter usando Commons IO

E finalmente - uma solução ainda mais rápida com o Apache Commons IO:

@Test
public void whenConvertingInputStreamToFile_thenCorrect4()
  throws IOException {
    InputStream initialStream = FileUtils.openInputStream
      (new File("src/main/resources/sample.txt"));

    File targetFile = new File("src/main/resources/targetFile.tmp");

    FileUtils.copyInputStreamToFile(initialStream, targetFile);
}

E aí está - 3 maneiras rápidas de gravarInputStream em um arquivo.