要在Java中實(shí)現(xiàn)局域網(wǎng)傳輸文件,可以使用Socket編程。以下是一個(gè)簡(jiǎn)單的示例代碼:
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; // 指定監(jiān)聽的端口
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"; // 服務(wù)器的IP地址
int port = 12345; // 服務(wù)器監(jiān)聽的端口
String fileToSend = "file_to_send.txt"; // 要發(fā)送的文件名
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());
}
}
}
在運(yùn)行時(shí),先啟動(dòng)服務(wù)器端,然后再啟動(dòng)客戶端??蛻舳藭?huì)將指定的文件發(fā)送到服務(wù)器端,并在控制臺(tái)上顯示發(fā)送成功的消息。服務(wù)器端會(huì)接收文件并保存在同一目錄下的"received_file.txt"文件中。
請(qǐng)注意,上述示例代碼僅僅演示了最基本的文件傳輸功能,并沒有考慮到文件的安全性、進(jìn)度更新、傳輸錯(cuò)誤處理等方面的問題。在實(shí)際應(yīng)用中,可能需要根據(jù)具體需求進(jìn)行擴(kuò)展和改進(jìn)。