¿Cómo puedo tomar una ByteArrayInputStream y tienen sus contenidos guardan como un archivo en el sistema de archivos

StackOverflow https://stackoverflow.com/questions/2824674

Pregunta

I tiene una imagen que está en la forma de un ByteArrayInputStream. Quiero aprovechar esto y hacer que sea algo que pueda guardar en un lugar en mi sistema de archivos.

he estado dando vueltas en círculos, ¿podría por favor me ayude.

¿Fue útil?

Solución

Si ya está usando Apache commons-io , puede hacerlo con:

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));

Otros consejos

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();

Se puede utilizar el siguiente 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();

tamponada escritor mejorará el rendimiento en la escritura de archivos en comparación con FileWriter.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top