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);
}
}
简易复制文件(IO)
最新推荐文章于 2022-07-11 22:48:23 发布