【发布时间】:2021-02-11 21:38:22
【问题描述】:
我正在尝试将一个大文件从我的计算机上传到不同网络中的另一台计算机。但是,文件传输速度非常慢。是什么导致我的代码出现瓶颈?
以下代码供上传者使用:
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 服务器的网络路径与您的网络路径不同,这可能会导致部分或全部速度差异。您可以使用
Files类中的copy()方法来简化并可能加快传输速度。
标签: java sockets stream network-programming