要在Java中實現局域網傳輸文件,可以使用Socket編程。以下是一個簡單的示例代碼:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) {
int port = 12345; // 指定監聽的端口
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Accepted connection from client: " + socket.getInetAddress());
try (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);
}
System.out.println("File received successfully.");
} catch (IOException e) {
System.out.println("Error receiving file: " + e.getMessage());
}
}
} catch (IOException e) {
System.out.println("Server error: " + e.getMessage());
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) {
String serverAddress = "192.168.1.100"; // 服務器的IP地址
int port = 12345; // 服務器監聽的端口
String fileToSend = "file_to_send.txt"; // 要發送的文件名
try (Socket socket = new Socket(serverAddress, port);
FileInputStream fileInputStream = new FileInputStream(fileToSend);
OutputStream outputStream = socket.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File sent successfully.");
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage());
}
}
}
在運行時,先啟動服務器端,然后再啟動客戶端。客戶端會將指定的文件發送到服務器端,并在控制臺上顯示發送成功的消息。服務器端會接收文件并保存在同一目錄下的"received_file.txt"文件中。
請注意,上述示例代碼僅僅演示了最基本的文件傳輸功能,并沒有考慮到文件的安全性、進度更新、傳輸錯誤處理等方面的問題。在實際應用中,可能需要根據具體需求進行擴展和改進。