我正在尝试将一个大文件从我的计算机上载到不同网络中的另一台计算机。然而,文件传输速度非常慢。是什么导致了我的代码中的瓶颈?
下面的代码是上传者的代码:
public static void main(String [] args) throws IOException {
/*
* Take a file, read it into a byte array using the File Input Stream
* Then send that byte array using a Buffered Output Stream
* Done
*/
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
File file = new File(fileToSend);
FileInputStream fis = new FileInputStream(file);
byte[] byteArray = fis.readAllBytes();
bos.write(byteArray);
bos.flush();
bos.close();
}下面是我用来下载这个文件的代码:
public static void main(String[] args) throws UnknownHostException, IOException {
/*
* Open up a socket, then get the byte array using a buffered input stream
* then use a file output stream to write out the file
*/
long start = System.currentTimeMillis();
Socket socket = new Socket(hostName, port);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] byteArray = bis.readAllBytes();
FileOutputStream fos = new FileOutputStream(fileOutput);
fos.write(byteArray);
long end = System.currentTimeMillis();
System.out.println("Download time: " + (end - start)/1000);
}我说的慢,我的意思是通过这个程序上传一个100MB的文件需要大约6-7分钟,而在google drive上上传甚至只需要一分钟。我还在尝试学习套接字服务器编程,所以请一定要让我知道瓶颈在哪里。
发布于 2020-10-29 21:26:05
您可以通过以下方式一次读取RAM中的所有字节:
byte[] byteArray = fis.readAllBytes();在此之后,您将所有字节写入套接字:
bos.write(byteArray);因此您必须等到从文件系统加载完所有100MB,然后才能等到这些字节被发送。在下载器中,你可以反过来做这件事。
您可以通过将这两个作业拆分成单独的线程来减少这一时间。
第一个线程从文件系统中连续读取n个字节(如1024),并将其存储在共享synchronizedList.
这些线程还可以通过PipedInputStream和PipedOutputStream相互通信:https://docs.oracle.com/javase/7/docs/api/java/io/PipedInputStream.html https://docs.oracle.com/javase/7/docs/api/java/io/PipedOutputStream.html
此外,您还可以使用像GZIP:https://docs.oracle.com/javase/7/docs/api/java/util/zip/GZIPOutputStream.html https://docs.oracle.com/javase/7/docs/api/java/util/zip/GZIPInputStream.html这样的压缩流。
您应该考虑使用A(自动)R(Esource)M(管理)-Blogs https://www.oracle.com/technical-resources/articles/java/trywithresources.html
https://stackoverflow.com/questions/64591195
复制相似问题