温馨提示×

java局域网传输文件

小云
99
2023-09-14 09:26:40
栏目: 编程语言

要在Java中实现局域网传输文件,可以使用Socket编程。以下是一个简单的示例代码:

  1. 创建一个服务器端,监听指定端口,接收文件。
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());
}
}
}
  1. 创建一个客户端,连接到服务器并发送文件。
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"文件中。

请注意,上述示例代码仅仅演示了最基本的文件传输功能,并没有考虑到文件的安全性、进度更新、传输错误处理等方面的问题。在实际应用中,可能需要根据具体需求进行扩展和改进。

0