import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CopyFiles extends JFrame implements ActionListener,Runnable{
public static void main(String[] args) {
CopyFiles cf=new CopyFiles();
}
JTextField tx1=new JTextField();
JTextField tx2=new JTextField();
JTextArea ta=new JTextArea();
CopyFiles(){
JFrame w=new JFrame();
w.setSize(450,500);
w.setLocationRelativeTo(null);
JLabel l1=new JLabel("源目录:");
JLabel l2=new JLabel("目标目录:");
JButton b1=new JButton("源目录");
JButton b2=new JButton("目标目录");
JScrollPane sp=new JScrollPane(ta);
JButton b3=new JButton("复制");
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(2,3));
p1.add(l1);
p1.add(tx1);
p1.add(b1);
p1.add(l2);
p1.add(tx2);
p1.add(b2);
w.setLayout(new BorderLayout());
w.add(p1,BorderLayout.NORTH);
w.add(sp,BorderLayout.CENTER);
w.add(b3,BorderLayout.SOUTH);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
w.setVisible(true);
}
@Override
public void run() {
copy(new File(tx1.getText()),new File(tx2.getText()));
}
public void copy(File f,File t){
String newDir=t.getPath()+"\\"+f.getName();
ta.append("正在创建目录"+newDir+"...\n");
File newDirFile=new File(newDir);
newDirFile.mkdir();
File sub[]=f.listFiles();
for(File s:sub){
if(s.isDirectory()){
copy(s,newDirFile);
}
if(s.isFile()){
ta.append("正在复制文件"+s+"...\n");
copyFile(s,new File(newDir+"/"+s.getName()));
}
}
}
public void copyFile(File from,File to){
try{
FileInputStream fis=new FileInputStream(from);
FileOutputStream fos=new FileOutputStream(to);
byte[] tmp=new byte[8192];
int len=fis.available()/8192;
for(int i=0;i<len;i++){
fis.read(tmp);
fos.write(tmp);
}
int size=fis.read(tmp);
fos.write(tmp,0,size);
fos.close();
}catch(Exception e){}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("源目录")){
JFileChooser jc=new JFileChooser();
jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jc.showOpenDialog(this);
File choosefile=jc.getSelectedFile();
if(choosefile.exists())
tx1.setText(choosefile.getPath());
}
if(e.getActionCommand().equals("目标目录")){
JFileChooser jc=new JFileChooser();
jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jc.showOpenDialog(this);
File choosefile=jc.getSelectedFile();
if(choosefile.exists())
tx2.setText(choosefile.getPath());
}
if(e.getActionCommand().equals("复制")){
Thread t=new Thread(this);
t.start();
}
}
}
java复制整个目录及文件
最新推荐文章于 2022-03-12 17:12:42 发布