`
hcmfys
  • 浏览: 345866 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

JAVA 复制 带进度条 时间 百分比

    博客分类:
  • java
阅读更多

 写得不太好。如果喜欢就下载
/**
 * @(#)JprogressBar.java
 * it can copy file
 * show speed remail time and copy precent      
 * @author hcmfys
 * @version 1.00 2008/5/9
 *把我们的智慧献给全人类
 */

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class JprogressBar extends JFrame implements Runnable {

    public JprogressBar() {
        initUI();
    }

    private void initUI() {
        btCopy = new JButton("open file....");
        JButton btCancel = new JButton("cancel");
        JButton btSavePath = new JButton("save Path...");
        copyFileProgressBar = new JProgressBar(0, 100);
        copyFileProgressBar.setPreferredSize(new Dimension(450, 15));
        copyFileProgressBar.setBackground(Color.GREEN);
        copyFileProgressBar.setForeground(Color.PINK);
        copyFileProgressBar.setStringPainted(true);
        copyFileProgressBar.setVisible(false);
        openFileDialog = new JFileChooser(".");
        this.setLayout(new BorderLayout());
        JPanel tmpPanel1 = new JPanel();
        JPanel tmpPanel2 = new JPanel();
        btCopy.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Thread t = new Thread(JprogressBar.this);
                t.start();
            }

        });
        btSavePath.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                savePath = setSavePath();
            }
        });
        btCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stop = true;
                btCopy.setEnabled(true);
            }
        });
        tmpPanel1.add(btCopy);
        tmpPanel1.add(btSavePath);
        tmpPanel1.add(btCancel);
        tmpPanel2.add(copyFileProgressBar);
        this.add(tmpPanel1, BorderLayout.NORTH);
        this.add(tmpPanel2, BorderLayout.SOUTH);
        this.setTitle("read and copy file");
        this.setPreferredSize(new Dimension(450, 95));
        this.pack();
        Dimension cd = centerIt(this);
        this.setLocation(cd.width, cd.height);
        final Dimension des = this.getPreferredSize();
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                stop = true;
                System.exit(0);
            }

            public void windowStateChanged(WindowEvent e) {
                System.out.println("ss");
                if (e.paramString().equals("WINDOW_STATE_CHANGED")) {
                    System.out.println("ss");
                    JprogressBar.this.setSize(des);
                }
            }
        });
        this.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
              //  System.out.println("ss");
              //  JprogressBar.this.setSize(des);
            }

        });
    }

    /*
    * start read file..
    */
    public void run() {
        stop = false;
        int c = openFileDialog.showOpenDialog(this);
        if (c == JFileChooser.APPROVE_OPTION) {
            try {
                File selectFile = openFileDialog.getSelectedFile();
                if (selectFile.equals(savePath)) {
                    JOptionPane.showMessageDialog(this, "  \t target file and source file can't as the same !");
                    return;
                }
                if (savePath == null) {
                    JOptionPane.showMessageDialog(this, "  \t please select a path to save file !");
                    return;
                }
                btCopy.setEnabled(false);
                copyFileProgressBar.setVisible(true);
                long size = selectFile.length();
                copyFileProgressBar.setMaximum((int) size);
                FileInputStream fin = new FileInputStream(selectFile);
                FileOutputStream fout = new FileOutputStream(savePath);
                byte[] buff = new byte[1024];
                int s;
                int count = 0;
                long startTime = System.currentTimeMillis();
                while ((s = fin.read(buff)) > 0 && !stop) {
                    count += s;
                    fout.write(buff, 0, s);
                    String str = "" + 100 * (count / (size + 0.01));
                    str = forMatString(str);
                    long endTime = System.currentTimeMillis();
                    String speedStr = getSpeed(count, startTime, endTime);
                    String remailTime = getRemailTime(count, size, startTime, endTime);
                    copyFileProgressBar.setString(" precent:   " + str + " %" + "    speed: " + speedStr + "    " + " remail  time : " + remailTime);
                    copyFileProgressBar.setValue(count);
                }
                fin.close();
                fout.close();
                if (!stop) {
                    JOptionPane.showMessageDialog(this, "  \t copy file complete  !");
                }
                stop = true;
                savePath = null;
                btCopy.setEnabled(true);
                copyFileProgressBar.setValue(0);
                copyFileProgressBar.setString("");
                copyFileProgressBar.setVisible(false);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "err:\n" + ex.getMessage());
            }
        }
    }

    /*
    *select  save file path
    */
    private File setSavePath() {
        File path = null;
        int c = openFileDialog.showSaveDialog(this);
        if (c == JFileChooser.APPROVE_OPTION) {
            path = openFileDialog.getSelectedFile();
        }
        return path;
    }

    /*
    * make frame center
    */
    private Dimension centerIt(Component c) {
        Dimension size = c.getSize();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int sH = screenSize.height;
        int sW = screenSize.width;
        int cW = size.width;
        int cH = size.height;
        return new Dimension((sW - cW) / 2, (sH - cH) / 2);
    }

    /*
    * show copy file  speed
    */
    private String getSpeed(long readByte, long startTime, long endTime) {
        long speed;
        if (endTime - startTime != 0) {
            speed = (readByte / (endTime - startTime)) * 1000;
            if (speed > 1024 * 1024) {
                return forMatString(speed / (1024 * 1024 + 0.1) + "") + " m/s";
            } else if (speed > 1024) {
                return forMatString(speed / (1024 + 0.1) + "") + " k/s";
            } else {
                return speed + " b/s";
            }
        } else {
            return "0 b/s";
        }
    }

    /*
    * format string
    */
    private String forMatString(String str) {
        String values;
        int index = str.indexOf(".");
        values = str.substring(0, index + 3);
        return values;
    }

    /*
    * get remail time
    */
    private String getRemailTime(long readByte, long totalByte, long startTime, long endTime) {
        long hour;
        long minute;
        long second;
        String h;
        String m;
        String s;
        try {
            long speed = readByte / (endTime - startTime);
            long time = ((totalByte - readByte) / speed) / 1000;
            hour = time / 3600;
            minute = time % 3600 / 60;
            second = time % 3600 % 60;
            h = hour + "";
            m = minute + "";
            s = second + "";
            if (hour < 10) {
                m = "0" + minute;
            }
            if (minute < 10) {
                m = "0" + minute;
            }
            if (second < 10) {
                s = "0" + second;
            }
            return h + ":" + m + ":" + s;
        } catch (Exception ex) {
            return "00:00:00";
        }

    }

    /*
    * show frm
    */

    public static void main(String[] args) {
        JprogressBar frm = new JprogressBar();
        frm.setVisible(true);
    }

    /*
    *
    */
    private JButton btCopy;
    private JFileChooser openFileDialog;
    private JProgressBar copyFileProgressBar;
    private File savePath = null;
    private boolean stop = false;
}


分享到:
评论
2 楼 hcmfys 2012-10-11  
lonuery 写道
open file 是获取要进行复制的文件的地址,save Path 复制到那个地方的地址,但是我复制了你的代码,为什么我复制代码运行后却复制不了呢?搞不懂你的代码,注释太少了,看的蛋疼!


:o  没有那么严重把!
1 楼 lonuery 2012-08-12  
open file 是获取要进行复制的文件的地址,save Path 复制到那个地方的地址,但是我复制了你的代码,为什么我复制代码运行后却复制不了呢?搞不懂你的代码,注释太少了,看的蛋疼!

相关推荐

Global site tag (gtag.js) - Google Analytics