Java

java怎么实现文件传输功能

小亿
143
2023-12-12 09:41:38
栏目: 编程语言

Java可以通过Socket编程实现文件传输功能。以下是一个简单的示例代码:

  1. 服务器端代码:
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();
    }
}
  1. 客户端代码:
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文件中。需要注意的是,实际开发中可能需要处理更多的异常情况,并考虑文件传输的安全性和效率等问题。

0
看了该问题的人还看了