java怎么實(shí)現(xiàn)文件傳輸功能

小億
130
2023-12-12 09:41:38

Java可以通過(guò)Socket編程實(shí)現(xiàn)文件傳輸功能。以下是一個(gè)簡(jiǎn)單的示例代碼:

  1. 服務(wù)器端代碼:
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();
    }
}

以上代碼實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的文件傳輸功能,服務(wù)器端將客戶端發(fā)送的文件保存到output.txt文件中。需要注意的是,實(shí)際開(kāi)發(fā)中可能需要處理更多的異常情況,并考慮文件傳輸?shù)陌踩院托实葐?wèn)題。

0