使用NIO对文件进行底层拷贝(按照字节)多线程技术初级应用 不阻塞程序运行
package com.lovo.homework01;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
/**
* 类:文件拷贝
* @author Abe
* NIO应用,JProgressBar应用
*/
@SuppressWarnings("serial")
public class NIOTest extends JFrame {
private JProgressBar jbar = null;
private int totleSize = 0;
private int copyedSize = 0;
private int eachSize = 0;
private JButton startButton = null;
private JTextField inField = null, outField = null;
/**
* 构造器
*/
public NIOTest() {
this.setSize(400, 300);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setLayout(null);
/**
* JProgressBar设置
*/
jbar = new JProgressBar();
jbar.setMinimum(0);
jbar.setMaximum(100);//显示上下限
jbar.setValue(0);//初始值
jbar.setStringPainted(true);//显示百分比
jbar.setBounds(50, 150, 300, 30);
/**
* 文字输入框
*/
inField = new JTextField();
inField.setBounds(50, 50, 300, 30);
outField = new JTextField();
outField.setBounds(50, 100, 300, 30);
/**
* 拷贝开始按钮
*/
startButton = new JButton("开始拷贝");
startButton.setBounds(150, 200, 100, 30);
/**
* 按钮加监听器,匿名内部类就地实例化
*/
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
/**
* 多线程技术 新建一个线程 就地实例化Runnable接口
*/
new Thread(new Runnable() {
@Override
public void run() {
//新建输入输出流 这里用Filexxxxxx 是因为NIO的方法他们才能用
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(inField.getText());
out = new FileOutputStream(outField.getText());
//NIO 专属 传输通道
FileChannel fcin = in.getChannel();
FileChannel fout = out.getChannel();
totleSize = in.available();
//NIO 专属 运输小车
ByteBuffer buffer = ByteBuffer.allocate(4096);
while ((eachSize = fcin.read(buffer)) != -1) {
//指针回零 然后开始读取数据 直到内容末尾
buffer.flip();
fout.write(buffer);
//清空小车
buffer.clear();
//设置 进度条显示内容
copyedSize += eachSize;
jbar.setValue((int) (100.0 * copyedSize / totleSize));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} 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();
}
}
}
}
}).start();//千万不要忘了 新建的线程 用这个开始运行
}
});
this.add(inField);
this.add(outField);
this.add(startButton);
this.add(jbar);
}
/**
* main方法 设置窗口可见
* @param args
*/
public static void main(String[] args) {
new NIOTest().setVisible(true);
}
}