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]);
}
}
You can move a file or directory by using the move(Path, Path, CopyOption...) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified. Empty directories can be moved.
FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With