Java 文件传输客户端带图形界面:文件选择和传输进度

本代码示例演示了如何使用Java Swing构建一个简单的文件传输客户端,该客户端提供文件选择和传输进度显示功能。

代码示例

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

public class FileTransferClient extends JFrame implements ActionListener {

    private static final String SERVER_IP = "219.218.21.89"; // 服务端IP
    private static final int SERVER_PORT = 8899; // 服务端端口

    private Socket client;
    private FileInputStream fis;
    private DataOutputStream dos;

    private JLabel fileLabel;
    private JButton fileButton;
    private JButton sendButton;
    private JProgressBar progressBar;

    public FileTransferClient() {
        super("文件传输Client端");

        // 初始化界面组件
        fileLabel = new JLabel("请选择文件");
        fileButton = new JButton("选择文件");
        sendButton = new JButton("发送");
        progressBar = new JProgressBar(0, 100);

        // 注册事件监听器
        fileButton.addActionListener(this);
        sendButton.addActionListener(this);

        // 添加组件到界面
        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        container.add(fileLabel, BorderLayout.WEST);
        container.add(fileButton, BorderLayout.CENTER);
        container.add(sendButton, BorderLayout.EAST);
        container.add(progressBar, BorderLayout.SOUTH);

        // 设置界面大小和位置
        setSize(400, 100);
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    /**
     * 选择文件事件处理
     * @param e
     */
    private void selectFile(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(FileTransferClient.this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            fileLabel.setText(file.getName());
        }
    }

    /**
     * 发送文件事件处理
     * @param e
     */
    private void sendFile(ActionEvent e) {
        try {
            File file = new File(fileLabel.getText());
            if (file.exists()) {
                // 建立连接
                client = new Socket(SERVER_IP, SERVER_PORT);

                // 初始化数据流
                fis = new FileInputStream(file);
                dos = new DataOutputStream(client.getOutputStream());

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

                // 开始传输文件
                System.out.println("======== 开始传输文件 =======");
                byte[] bytes = new byte[1024];
                int length = 0;
                long progress = 0;
                while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                    dos.write(bytes, 0, length);
                    dos.flush();
                    progress += length;
                    progressBar.setValue((int) (100 * progress / file.length()));
                }
                System.out.println();
                System.out.println("======== 文件传输成功 =======");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
                if (dos != null)
                    dos.close();
                if (client != null)
                    client.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 按钮事件处理
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == fileButton) {
            selectFile(e);
        } else if (e.getSource() == sendButton) {
            sendFile(e);
        }
    }

    /**
     * 入口
     * @param args
     */
    public static void main(String[] args) {
        new FileTransferClient();
    }

}

代码说明

  1. 创建图形界面:使用 JFrame 创建主窗口,并添加 JLabel、JButton 和 JProgressBar 组件,分别用于显示文件名、选择文件、发送文件和显示传输进度。

  2. 事件监听:使用 ActionListener 监听 JButton 的点击事件,分别实现文件选择和文件发送功能。

  3. 文件选择:使用 JFileChooser 打开文件选择对话框,并将选中的文件名显示在 fileLabel 上。

  4. 文件传输:

    • 使用 Socket 建立与服务器的连接。
    • 使用 FileInputStream 和 DataOutputStream 进行文件读取和数据发送。
    • 首先发送文件名和文件大小。
    • 循环读取文件内容,并通过 dos.write() 将数据发送给服务器。
    • 使用 progressBar.setValue() 更新传输进度条。

注意事项

  • 该示例代码仅演示了简单的文件传输和进度显示,实际应用中可能需要添加更多功能,例如错误处理、传输速度显示等。
  • 服务器端的代码需与客户端代码对应,才能实现完整的文件传输功能。
  • 请根据实际需求修改服务端IP地址和端口号。

总结

本代码示例演示了如何使用Java Swing构建简单的文件传输客户端,并添加图形界面以提升用户体验。通过学习本代码,您可以了解如何使用Java Swing构建图形界面、处理事件以及进行文件传输等操作。

Java 文件传输客户端带图形界面:文件选择和传输进度

原文地址: https://www.cveoy.top/t/topic/ocsH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录