在Java中,可以通過Socket來傳輸大文件。以下是一個簡單的例子來說明如何在Java中使用Socket傳輸大文件:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("received_file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
File file = new File("large_file.txt");
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
socket.close();
}
}
在上面的代碼中,服務器端監聽端口12345,客戶端連接到服務器端的12345端口。客戶端發送名為"large_file.txt"的大文件到服務器端,并且服務器端接收并保存為"received_file.txt"文件。
通過Socket傳輸大文件時,需要注意以下幾點: