2010-05-13 17 views

Respuesta

12

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

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

Ya. Mucho más limpio – SingleShot

+0

Esto es genial, pero descubrí que necesitaba crear el FileoutputStream fuera de la llamada para copiarlo y poder cerrarlo. Algunas de las IOUtils descargan el búfer, pero estaba teniendo este problema de que los archivos de salida no se podían abrir a veces. Una vez que agregué una llamada para cerrar() en FileOutputStream, funcionó de maravilla. En general, estoy muy contento de haber encontrado el material de IOUtils, lo he estado usando también para otras cosas. – titania424

2

Usted 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); 
} 
+0

Gracias Gaurav, lo intentaré ahora. – Ankur

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

escritor Buffered mejorará el rendimiento al escribir archivos en comparación con FileWriter.

+1

Los escritores son para archivos de caracteres, no archivos binarios –

Cuestiones relacionadas