BufferedInputStream into byte[] to be send over a Socket to a Database BufferedInputStream into byte[] to be send over a Socket to a Database arrays arrays

BufferedInputStream into byte[] to be send over a Socket to a Database


Have a look at ByteArrayOutputStream:Java 7 API java.io.ByteArrayOutputStream

bytesOut = new ByteArrayOutputStream();byte[] bytes = bytesOut.toByteArray();

Update:If you insist on doing what you are doing you can just assign the intermediate ByteArrayOutputStream to a variable and get hold of the array that way:

ByteArrayOutputStream bytesOut = new ByteArrayOutputStream()BufferedOutputStream out = new BufferedOutputStream(bytesOut);copy(in, out);return bytesOut.toByteArray();

Update 2:The real question seems to be how to copy a file without reading it all into memory first:

1) Manually:

    byte[] buff = new byte[64*1024]; //or some size, can try out different sizes for performance    BufferedInputStream in = new BufferedInputStream(new FileInputStream("fromFile"));    BufferedOutputStream out = new BufferedOutputStream(new FileoutputStream("toFile"));    int n = 0;    while ((n = in.read(buff)) >= 0) {        out.write(buff, 0, n);    }    in.close();    out.close();

2) Efficiently by the OS and no loop etc:

FileChannel from = new FileInputStream(sourceFile).getChannel();FileChanngel to = new FileOutputStream(destFile).getChannel();to.transferFrom(from, 0, from.size());//or from.transferTo(0, from.size(), to);from.close();to.close();

3) If you have Java 7 you can simplify exception and stream closing or just copy the file with the new APIs i in java 7:

java.nio.file.Files.copy(...);

see java.nio.file.Files


DataFetcher would be perfect for this:

http://tus.svn.sourceforge.net/viewvc/tus/tjacobs/io/DataFetcher.java?revision=34&view=markup

You can use clearBuffer to clear out the buffer between reads if you are running out of memory

You'll also need the Timeout class - it's in the same project in the same package.