我正在尝试使用 Java 将文件从一台计算机发送到另一台计算机。我已经编写了下面的代码,如果发送者和接收者都在同一台计算机上启动,但如果它们在不同的机器上工作,则接收文件大小大于原始文件并且已损坏。
注意:我正在尝试传输最大 10 MB 的文件。
我怎样才能解决这个问题?
发件人:
ServerSocket server_socket = new ServerSocket(8989);
File myFile = new File(myPath);
Socket socket = server_socket.accept();
int count;
byte[] buffer = new byte[1024];
OutputStream out = socket.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(myFile));
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
out.flush();
}
socket.close();
接收者:
Socket socket = new Socket(address, 8989);
FileOutputStream fos = new FileOutputStream(anotherPath);
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = socket.getInputStream();
while((count=in.read(buffer)) >0){
fos.write(buffer);
}
fos.close();
socket.close();