Como faço para pegar um bytearrayInputStream e ter seu conteúdo salvo como um arquivo no sistema de arquivos
-
26-09-2019 - |
Pergunta
Eu tenho uma imagem que está na forma de um bytearrayInputStream. Quero pegar isso e fazer algo que eu possa economizar em um local no meu sistema de arquivos.
Eu tenho andado em círculos, você poderia me ajudar.
Solução
Se você já está usando o Apache Commons-io, você pode fazer isso com:
IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));
Outras dicas
InputStream in = //your ByteArrayInputStream here
OutputStream out = new FileOutputStream("filename.jpg");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Você pode usar o seguinte código:
ByteArrayInputStream input = getInputStream();
FileOutputStream output = new FileOutputStream(outputFilename);
int DEFAULT_BUFFER_SIZE = 1024;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);
while (n >= 0) {
output.write(buffer, 0, n);
n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);
}
ByteArrayInputStream stream = <<Assign stream>>;
byte[] bytes = new byte[1024];
stream.read(bytes);
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("FileLocation")));
writer.write(new String(bytes));
writer.close();
O escritor buffer melhorará o desempenho ao escrever arquivos em comparação com o FileWriter.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow