Come faccio a prendere un ByteArrayInputStream e avere i suoi contenuti salvati in un file sul filesystem

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

Domanda

Ho un'immagine che è nella forma di un ByteArrayInputStream. Voglio prendere questo e fare qualcosa che posso salvare una posizione nel mio file system.

mi è stato girare a vuoto, la prego di darmi una mano.

È stato utile?

Soluzione

Se si sta già utilizzando Apache commons-io , è possibile farlo con:

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

Altri suggerimenti

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

È possibile utilizzare il seguente codice:

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

Buffered Writer migliorerà le prestazioni in scrittura di file rispetto a FileWriter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top