阅读量:3
要实现Java的离线文件传输,可以使用Socket编程来实现。下面是一个简单的离线文件传输的示例代码:
服务端代码:
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("等待客户端连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端已连接"); // 接收文件 InputStream in = socket.getInputStream(); FileOutputStream out = new FileOutputStream("file.txt"); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); System.out.println("文件接收完成"); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
客户端代码:
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); // 发送文件 File file = new File("file.txt"); FileInputStream in = new FileInputStream(file); OutputStream out = socket.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); System.out.println("文件发送完成"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
以上代码中,服务端通过ServerSocket
监听指定的端口,客户端通过Socket
连接到服务端。客户端将文件读取为字节流,通过Socket
的输出流发送给服务端,服务端接收数据并写入文件。