Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to transfer a file using Java?

Tags:

java

file-io

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]);
    }
}
like image 351
jjnguy Avatar asked Nov 10 '08 07:11

jjnguy


People also ask

How do you move a file in Java?

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.

What is the best way to write to a file in Java?

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.


1 Answers

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.)

like image 159
Jon Skeet Avatar answered Oct 05 '22 10:10

Jon Skeet