使用Java传输文件的最佳方法是什么?

时间:2022-08-22 18:10:43

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:

Util方法如下:

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]);
    }
}

1 个解决方案

#1


16  

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

一次读取一个字节将是非常低效的。你也依赖于可用,这很少是一个好主意。 (如果当前没有可用的字节,它将返回0,但可能还会有更多字节。)

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

(调用者应关闭两个流。)

#1


16  

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

一次读取一个字节将是非常低效的。你也依赖于可用,这很少是一个好主意。 (如果当前没有可用的字节,它将返回0,但可能还会有更多字节。)

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

(调用者应关闭两个流。)