What is the best way to transfer files using Java?
•
Java
I'm writing a code to upload files from the client to my server, and the performance is not as fast as I think
I am now executing the code segment of file transfer. I want to know how to speed up the transfer
Sorry, all codes:
InputStream fileItemInputStream ; OutputStream saveFileStream; int[] buffer; while (fileItemInputStream.available() > 0) { buffer = Util.getBytesFromStream(fileItemInputStream); Util.writeIntArrToStream(saveFileStream,buffer); } saveFileStream.close(); fileItemInputStream.close();
Util method is 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]); } }
Solution
Reading one byte at a time would be very inefficient You also rely on availability, which is rarely a good idea (if no bytes are currently available, 0 is returned, but more bytes may be available.)
This is the correct code for the copy stream:
public void copyStream(InputStream input,OutputStream output) throws IOException { byte[] buffer = new byte[32*1024]; int bytesRead; while ((bytesRead = input.read(buffer,buffer.length)) > 0) { output.write(buffer,bytesRead); } }
(the caller should close both streams.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码