简易复制文件(IO)

package com.lovo;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class MyFrame2 extends JFrame {
	private int totalSize = 0;
	private int totalCopy = 0;
	
	private JTextField srcField, targetField;
	private JProgressBar bar;
	private JButton copyButton;
//	private JFileChooser srcChooser, targertField;

	public MyFrame2() {
		this.setTitle("文件拷贝");
		this.setSize(320, 150);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

		this.setLayout(new FlowLayout(FlowLayout.LEFT));		
		srcField = new JTextField(18);
		targetField = new JTextField(18);
		bar = new JProgressBar();
		bar.setMinimum(0);
		bar.setMaximum(100);
		bar.setValue(0);
		bar.setStringPainted(true);
		copyButton = new JButton("拷贝");
		copyButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				bar.setValue(0);
				totalSize = 0;
				totalCopy = 0;
				copyButton.setEnabled(false);
				new Thread(new Runnable() {
					@Override
					public void run() {
						InputStream in = null;
						OutputStream out = null;
						try {
							in = new FileInputStream(srcField.getText());
							totalSize = in.available();
							out = new FileOutputStream(targetField.getText());
							byte[] buffer = new byte[4096];
							int bytesToRead;
							while((bytesToRead = in.read(buffer)) != -1) {
								out.write(buffer, 0, bytesToRead);
								totalCopy += bytesToRead;
								bar.setValue((int) (totalCopy / (double)totalSize * 100));
							}
						}
						catch (IOException e) {
							e.printStackTrace();
						}
						finally {
							if (in != null) {
								try {
									in.close();
								}
								catch (IOException e) {
									e.printStackTrace();
								}
							}
							if (out != null) {
								try {
									out.close();
								}
								catch (IOException e) {
									e.printStackTrace();
								}
							}
							copyButton.setEnabled(true);
						}
					}
				}).start();
			}
		});

		this.add(srcField);
		this.add(targetField);
		this.add(bar);
		this.add(copyButton);		

	}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值