tags:

views:

1606

answers:

1

I am writing code for uploading a file from a client to my server and the performance isn't as fast as I think it should be.

I have the current code snippet that is doing the file transfer and I was wondering how I could speed up the transfer.

Sorry about all of the code:

InputStream fileItemInputStream ;
OutputStream saveFileStream;
int[] buffer;
while (fileItemInputStream.available() > 0) {
    buffer = Util.getBytesFromStream(fileItemInputStream);
    Util.writeIntArrToStream(saveFileStream, buffer);
}
saveFileStream.close();
fileItemInputStream.close();

The Util methods are as follows:

public static int[] getBytesFromStream(InputStream in, int size) throws IOException {
    int[] b = new int[size];
    int count = 0;
    while (count < size) {
        b[count++] = in.read();
    }
    return b;
}

and:

public static void writeIntArrToStream(OutputStream out, int[] arrToWrite) throws IOException {
    for (int i = 0; i < arrToWrite.length; i++) {
        out.write(arrToWrite[i]);
    }
}
+9  A: 

Reading a single byte at a time will be horribly inefficient. You're also relying on available, which is rarely a good idea. (It will return 0 if there are no bytes currently available, but there may be more to come.)

This is the right sort of code to copy a stream:

public void copyStream(InputStream input, OutputStream output) throws IOException
{
    byte[] buffer = new byte[32*1024];
    int bytesRead;
    while ((bytesRead = input.read(buffer, 0, buffer.length)) > 0)
    {
        output.write(buffer, 0, bytesRead);
    }
}

(The caller should close both streams.)

Jon Skeet
don't I have to worry about my unsigned bytes in the file overflowing in Java's signed bytes?
jjnguy
They are mp3 files, if it matters
jjnguy
No, you don't. This is just reading and writing, not performing any sort of arithmetic or transformation.
Jon Skeet
And/or look into using the BufferedInput/OutputStream classes.
John Gardner
very good approach
madicemickael