java实现在复制文件时使用进度条(java实现进度条)

时间:2022-05-12 09:23:11

思路分析:

因为既要有操作面板又要有进度条,所以肯定要出现两个继承JFrame类的窗体。
先看被调用的进度条窗体,它不需要手动操作,所以类的内部实现一个方法就可以了。因为设计文件操作,所以要捕获异常。首先根据要复制的文件创建File对象,以及根据复制后文件的保存地址创建File对象,然后创建FileOutputStream对象,再创建FileInputStream对象,之后是ProgressMonitorInputStream对象,然后读取文件,如果总耗时超过2秒,将会自动弹出一个进度监视窗口。接下来定义byte数组,再使用while循环读取文件,使用FileOutputStream类的write()方法通过流写数据,再使用FileOutputStream类的close()方法关闭输出流,最后使用ProgressMonitorInputStream类的close()方法关闭输入流。可见该方法需要三个参数:弹出它的父窗口、要复制的文件地址以及要复制到的文件夹。
代码如下:

ProgressMonitorTest.java:

 

复制代码代码如下:

package cn.edu.xidian.crytoll;
import java.io.FileInputStream;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.ProgressMonitorInputStream;
public class ProgressMonitorTest {

    public void useProgressMonitor(JFrame frame, String copyPath, String newPath) {
        try {
            File file = new File(copyPath); // 根据要复制的文件创建File对象
            File newFile = new File(newPath); // 根据复制后文件的保存地址创建File对象
            FileOutputStream fop = new FileOutputStream(newFile); // 创建FileOutputStream对象
            InputStream in = new FileInputStream(file);
            // 读取文件,如果总耗时超过2秒,将会自动弹出一个进度监视窗口。
            ProgressMonitorInputStream pm = new ProgressMonitorInputStream(
                    frame, "文件读取中,请稍后...", in);
            int c = 0;
            byte[] bytes = new byte[1024]; // 定义byte数组
            while ((c = pm.read(bytes)) != -1) { // 循环读取文件
                fop.write(bytes, 0, c); // 通过流写数据
            }
            fop.close(); // 关闭输出流
            pm.close(); // 关闭输入流
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 

3. 再看主窗体。JLabel、JTextField神马的就不用说了,选择文件和选择文件夹这两个按钮也是老生常谈了,最重要的是“开始复制”按钮,将由它来负责弹出这个进度条,这就需要开辟一个新的线程,所以主窗体不仅要继承JFrame类,还要实现Runnable接口。他大爷的。

4. 在开始复制按钮的具体方法里,首先创建一个Thread对象作为新的线程,然后调用该对象的start()方法,重载执行run()方法,在该方法中创建一个进度条对象,使用JTextField类的getText()方法获取要复制的文件地址和要复制到的路径,然后调用进度条类里的方法。

代码如下:

 

复制代码代码如下:

package cn.edu.xidian.crytoll;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

public class UserMonitorFrame extends JFrame implements Runnable{

    /**
     * 
     */
    private static final long serialVersionUID = 8674569541853793419L;
    private JPanel contentPane;
    private JTextField fileField;
    private JTextField searchTextField;
    private JTextField replaceTextField;
    private File file;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UserMonitorFrame frame = new UserMonitorFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public UserMonitorFrame() {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 501, 184);
        setTitle("在读取文件时使用进度条");
        getContentPane().setLayout(null);

        JLabel label = new JLabel("\u6587\u4EF6\u5730\u5740\uFF1A");
        label.setBounds(10, 10, 70, 15);
        getContentPane().add(label);

        textField = new JTextField();
        textField.setBounds(90, 7, 300, 21);
        getContentPane().add(textField);
        textField.setColumns(10);

        JButton button = new JButton("\u9009\u62E9\u6587\u4EF6");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_actionPerformed(e);
            }
        });
        button.setBounds(400, 6, 93, 23);
        getContentPane().add(button);

        JLabel label_1 = new JLabel("\u590D\u5236\u5730\u5740\uFF1A");
        label_1.setBounds(10, 40, 70, 15);
        getContentPane().add(label_1);

        textField_1 = new JTextField();
        textField_1.setBounds(90, 38, 300, 21);
        getContentPane().add(textField_1);
        textField_1.setColumns(10);

        JButton button_1 = new JButton("\u9009\u62E9\u5730\u5740");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_1_actionPerformed(e);
            }
        });
        button_1.setBounds(400, 39, 93, 23);
        getContentPane().add(button_1);

        JButton button_2 = new JButton("\u5F00\u59CB\u590D\u5236");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_copyButton_actionPerformed(e);
            }
        });
        button_2.setBounds(182, 69, 93, 23);
        getContentPane().add(button_2);
    }
    protected void do_button_actionPerformed(ActionEvent e){
        JFileChooser chooser=new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        // 显示文件打开对话框
        int option = chooser.showOpenDialog(this);
        // 确定用户按下打开按钮,而非取消按钮
        if (option != JFileChooser.APPROVE_OPTION)
            return;
        // 获取用户选择的文件对象
        file = chooser.getSelectedFile();
        // 显示文件信息到文本框
        textField.setText(file.toString());
    }
    protected void do_button_1_actionPerformed(ActionEvent e){
        JFileChooser chooser=new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option=chooser.showOpenDialog(this);
        if(option!=JFileChooser.APPROVE_OPTION)
            return;
        file=chooser.getSelectedFile();
        textField_1.setText(file.toString());
    }
  //确定复制按钮单击事件
    protected void do_copyButton_actionPerformed(ActionEvent arg0) {
       Thread thread = new Thread(this);
       thread.start();
    }
   //应用多线程技术实现读取操作
    @Override
    public void run() {
        ProgressMonitorTest test = new ProgressMonitorTest();
        String path = textField.getText();
        String save = textField_1.getText();
        test.useProgressMonitor(this,path,save+path.substring(path.lastIndexOf("."),path.length()));

    }
}