Java可以通過Socket編程實現文件傳輸功能。以下是一個簡單的示例代碼:
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
FileOutputStream out = new FileOutputStream("output.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
File file = new File("input.txt");
FileInputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
in.close();
socket.close();
}
}
以上代碼實現了一個簡單的文件傳輸功能,服務器端將客戶端發送的文件保存到output.txt文件中。需要注意的是,實際開發中可能需要處理更多的異常情況,并考慮文件傳輸的安全性和效率等問題。