通过JFileChooser完成文件的拷贝

来源:互联网 发布:自媒体发展的数据 编辑:程序博客网 时间:2024/06/05 19:30

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 拷贝文件
 * @author martin

 */
public class CopyFile {

    /**
     * 完成文件的拷贝
     * @param source 源文件             E:/lyc/ITMS_H_0407/record/2010/4/10/0217940.wav
     * @param destination 目标文件    E:/lyc/ITMS_H_0407/record/2010/4/9/0217940.wav
     * @throws IOException
     */
    public static void fileCopy(HashMap<Integer, String> hashMap, String dest) throws IOException{
        Iterator<Integer> iterator = hashMap.keySet().iterator();
        while(iterator.hasNext()) {

            String source = hashMap.get(iterator.next());
            String destination = dest;
            if(source != null) {

                destination += "/" + new File(source).getName();
                // Create channel on the source
                FileChannel srcChannel = new FileInputStream(source).getChannel();

 

                // Create channel on the destination
                FileChannel dstChannel = new FileOutputStream(destination).getChannel();

 

                // Copy file contents from source to destination
                //dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.transferTo(0, srcChannel.size(), dstChannel);

 

                // Close the channels
                srcChannel.close();
                dstChannel.close();
            }
        }
    }

——————————————————下面为调用部分(Start)————————————————

    /**
     * 执行备份
     * @param evt
     */
    private void btnBackupActionPerformed(ActionEvent evt) {
        JFileChooser fileChooser = new JFileChooser();           //实例化一个文件选择器
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  //只能选择目录

        /*fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);        //只能选择文件*/
        fileChooser.showOpenDialog(this);
        try{
            if(fileChooser.getSelectedFile() != null) {                    //获取选择的目录或文件
                CopyFile.fileCopy(hashMap, fileChooser.getSelectedFile().getAbsolutePath());
                JOptionPane.showMessageDialog(null, "完毕,共计"+hashMap.size()+"个文件);
            }
        } catch(IOException e) {
            JOptionPane.showMessageDialog(null, "失败!", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

——————————————————上面为调用部分(End)————————————————

原创粉丝点击