下面是一个比较简单的文件复制器
1.复制的具体实现方法
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 指定位置的文件复制到指定位置. * @author Administrator * */ public class fileCopy { // 文件复制的方法 public void copyFile(String scrPath, String desPath) { // 如果路径正确,得到源文件以及目标文件 try { FileInputStream fis = new FileInputStream(scrPath); FileOutputStream fos = new FileOutputStream(desPath); //读取文件,并将读取到的数据直接写入磁盘. try { int read = fis.read(); while (read != -1) { //将读取的数据直接写到磁盘当中 fos.write((byte)read); read = fis.read(); } //关闭流 fis.close(); //保证数据能完整写入到磁盘当中 fos.flush(); //关闭流 fos.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
2.界面
import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class fileCopyUI extends JFrame{ public static void main(String args[]){ fileCopyUI ui = new fileCopyUI(); ui.showUI(); } public void showUI(){ this.setTitle("文件复制器"); this.setSize(300,125); JButton but = new JButton("复制"); JLabel jl = new JLabel(" 源文件:"); JTextField jf = new JTextField(20); JLabel jl1 = new JLabel("目标文件:"); JTextField jf1 = new JTextField(20); this.add(jl); this.add(jf); this.add(jl1); this.add(jf1); this.add(but); this.setLayout(new FlowLayout()); this.setLocationRelativeTo(null); //居中显示 this.setResizable(false);//不可改变大小 this.setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭界面时推出程序 this.setVisible(true);//显示界面 ActionListenerImpl l = new ActionListenerImpl(jf,jf1); but.addActionListener(l); } }
3.监听器
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JTextField; public class ActionListenerImpl implements ActionListener { private JTextField jf; private JTextField jf1; // 获取文件指定的路径和关键字 public ActionListenerImpl(JTextField jf, JTextField jf1) { this.jf = jf; this.jf1 = jf1; } public void actionPerformed(ActionEvent e) { JButton but = (JButton)e.getSource(); if(but.getText().equals("复制")){ fileCopy fc = new fileCopy(); fc.copyFile(jf.getText(), jf1.getText()); } } }