Java实现文件传输

服务端发送,客户端接收。服务端持续运行,一旦有客户端连接就会向客户端发送文件

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 文件传输server(由服务器发送)
 *
 * @author qxt
 * @date 2021/3/8 17:38
 */
public class SendExaminationPaperServer extends ServerSocket {
    /**
     * 服务器端口
     */
    private static final int SERVER_PORT = 8888;
    /**
     * 文件路径
     */
    private String fileURL;

    private ServerSocket server;

    public SendExaminationPaperServer(String fileURL) throws Exception {
        super(SERVER_PORT);
        this.server = this;
        this.fileURL = fileURL;
        System.out.println("ip:  "+server.getInetAddress());
    }

    /**
     * 等待连接
     *
     * @throws Exception
     */
    public void waiting() throws Exception {
        File file = new File(fileURL);
        while (true) {
            //当阻塞时接受新的连入请求
            Socket client = this.accept();
            //并建立新的线程进行处理
            new Handler(client, file);
        }
    }

    /**
     * 线程处理类
     *
     * @author Walskor
     */
    private static class Handler implements Runnable {
        private Socket socket;
        private FileInputStream fileIn;
        private DataOutputStream DataOUT;
        private File file;

        public Handler(Socket client, File file) {
            this.socket = client;
            this.file = file;
            new Thread(this).start();
        }

        @Override
        public void run() {
            try {
                sendFile(file);  //传输文件
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        socket = null;
                        System.out.println("Finally error: " + e.getMessage());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 向客户端传输文件
         *
         * @throws Exception
         */
        private void sendFile(File file) throws Exception {
            try {
                if (file.exists()) {
                    fileIn = new FileInputStream(file);
                    DataOUT = new DataOutputStream(socket.getOutputStream());

                    //文件名和长度
                    DataOUT.writeUTF(file.getName());
                    DataOUT.flush();
                    DataOUT.writeLong(file.length());
                    DataOUT.flush();

                    //开始传输文件
                    System.out.println("=========Start to transfer=========");
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    long progress = 0;
                    while ((length = fileIn.read(bytes, 0, bytes.length)) != -1) {
                        DataOUT.write(bytes, 0, length);
                        DataOUT.flush();
                        progress += length;
                        System.out.println("| " + (100 * progress / file.length()) + "% |");
                    }
                    System.out.println();
                    System.out.println("=====File transferred successfully=====");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {                                //关闭数据流
                if (fileIn != null) {
                    fileIn.close();
                }
                if (DataOUT != null) {
                    DataOUT.close();
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Server starting...");
        try {
            SendExaminationPaperServer transfer = new SendExaminationPaperServer("文件路径");
            transfer.waiting();
            if (transfer != null) {
                transfer.close();
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.RoundingMode;
import java.net.Socket;
import java.text.DecimalFormat;

/**
 * 文件接收端 Client(由服务器发送)
 *
 * @author qxt
 * @date 2021/3/8 17:38
 */
public class ReceiveExaminationPaperClient extends Socket {
    /**
     * 服务端IP
     */
    private static final String SERVER_IP = "localhost";
    /**
     * 服务端端口号
     */
    private static final int SERVER_PORT = 8888;
    private Socket server;
    private DataOutputStream outputStream;
    /**
     * 保存接收的文件的文件夹路径
     */
    private final String directoryURL;

    public ReceiveExaminationPaperClient(String directoryURL) throws Exception {
        super(SERVER_IP, SERVER_PORT);
        this.directoryURL = directoryURL;
        this.server = this;
        this.outputStream = new DataOutputStream(
                server.getOutputStream());
        System.out.println("this cilent[port:" + this.getLocalPort() + "] attach to server successfully");
    }

    /**
     * 发送参数
     *
     * @throws Exception
     */
    public void send() throws Exception {
        outputStream.writeUTF("假装这是一条有用的数据流");
        //清空数据流
        outputStream.flush();
    }

    /**
     * 接收文件
     */
    public void receive() {
        LoadFile loadFile = new LoadFile(this, directoryURL);
        loadFile.get();
        System.out.println("end of load");
    }

    private static class LoadFile {
        private Socket socket;
        public String fileName;
        public long fileLength;
        private DataInputStream diStream;
        private FileOutputStream foStream;
        private static DecimalFormat dFormat;
        private final String directoryURL;

        static {
            dFormat = new DecimalFormat("#0.0");
            dFormat.setRoundingMode(RoundingMode.HALF_UP);
            dFormat.setMinimumFractionDigits(1);
            dFormat.setMaximumFractionDigits(1);
        }//设置数字格式,保留一位有效数字

        public LoadFile(Socket socket, String directoryURL) {
            this.socket = socket;
            this.directoryURL = directoryURL;
        }

        public void get() {
            try {
                diStream = new DataInputStream(socket.getInputStream());

                //文件名和长度
                fileName = diStream.readUTF();
                fileLength = diStream.readLong();
                File directory = new File(directoryURL);
                if (!directory.exists()) {
                    directory.mkdir();
                }
                File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
                foStream = new FileOutputStream(file);

                //开始接收文件
                byte[] bytes = new byte[1024];
                int length = 0;
                while ((length = diStream.read(bytes, 0, bytes.length)) != -1) {
                    foStream.write(bytes, 0, length);
                    foStream.flush();
                }
                System.out.println("File received [ File Name: " + fileName + " ] [ Size: " + getFormatFileSize(fileLength) + " ] ===");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (foStream != null) {
                        foStream.close();
                    }
                    if (diStream != null) {
                        diStream.close();
                    }
                    socket.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

            }// end try

        }// end get

        /**
         * 格式化文件大小
         *
         * @param length
         * @return
         */
        private String getFormatFileSize(long length) {
            double size = ((double) length) / (1 << 30);
            if (size >= 1) {
                return dFormat.format(size) + "GB";
            }
            size = ((double) length) / (1 << 20);
            if (size >= 1) {
                return dFormat.format(size) + "MB";
            }
            size = ((double) length) / (1 << 10);
            if (size >= 1) {
                return dFormat.format(size) + "KB";
            }
            return length + "B";
        }
    }

    public static void main(String[] args) {
        String directoryURL = "保存文件的文件夹路径";
        try {
            ReceiveExaminationPaperClient client = new ReceiveExaminationPaperClient(directoryURL);
            client.receive();
            //关闭数据流
            if (client.outputStream != null) {
                try {
                    client.outputStream.close();
                } catch (Exception e) {
                    client.outputStream = null;
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过Socket实现文件传输。下面是一个简单的示例代码: 服务端代码: ```java public class FileServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("等待客户端连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端已连接"); DataInputStream dis = new DataInputStream(socket.getInputStream()); String fileName = dis.readUTF(); long fileLength = dis.readLong(); FileOutputStream fos = new FileOutputStream("D:\\" + fileName); byte[] bytes = new byte[1024]; int length; while ((length = dis.read(bytes, 0, bytes.length)) != -1) { fos.write(bytes, 0, length); fos.flush(); } System.out.println("文件接收成功"); fos.close(); dis.close(); socket.close(); serverSocket.close(); } } ``` 客户端代码: ```java public class FileClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1", 8888); String fileName = "test.txt"; File file = new File("D:\\" + fileName); FileInputStream fis = new FileInputStream(file); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(file.getName()); dos.flush(); dos.writeLong(file.length()); dos.flush(); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes, 0, bytes.length)) != -1) { dos.write(bytes, 0, length); dos.flush(); } System.out.println("文件发送成功"); fis.close(); dos.close(); socket.close(); } } ``` 这是一个简单的示例代码,你可以根据需求进行修改和扩展。注意,这种方式仅适合传输小文件,如果要传输大文件,需要进行分割和组合,或者使用其他方式,如FTP等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值