copy

介绍了一个使用Java编写的文件及目录复制工具,该工具能够高效地处理小到大容量文件的复制工作,并提供了友好的GUI界面供用户选择源文件夹与目标文件夹,实时显示复制进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class JCopy {

	
	public static long size_total = 0;
	public static long size_copy = 0;
	public static int percent_process = 0;//进度百分比
	public static JProgressBar jbar;
	public static Container p;
	public static JLabel label_jbar;
	public static JLabel label_result;
	public static JButton confirm;
	
	public static String toUnit(long size){
		if (size>0) {
			if (size<1000) {
				return size+"B";
			}else if (size<1000000l) {
				size=size/1000l;
				return size+"K";
			}else if (size<1000000000l) {
				size=size/1000000l;
				return size+"M";
			}else {
				size=size/1000000000l;
				return size+"G";
			}
		}else {
			return 0+"B";
		}
	}
	/**
	 * 复制单个
	 * @param file_src
	 * @param directory_dest
	 */
	public static void copyOne(final File file_src,final File directory_dest){
		if (file_src.exists()&&file_src.isFile()) {
			size_total=file_src.length();
			new Thread(new Runnable() {
				
				public void run() {
					long s = System.currentTimeMillis(); 
					File file_dest = new File(directory_dest,file_src.getName());
					if (file_src.length()<1024*1024*100) {
						copyChannel(file_src, file_dest);
					}else {
						copyBigFile(file_src, file_dest);
					}
					long e = System.currentTimeMillis(); 
					long a = (e-s)/1000;
					long b = size_total/(1024*1024);
					long c = new Double(b/a).longValue();
					label_result.setText("耗时"+a+"秒,"+c+"M/s");
				}
			}).start();
			new Thread(new Runnable() {
				
				public void run() {
					File file_dest = new File(directory_dest,file_src.getName());
					boolean bool = true;
					while (bool) {
						if (file_dest.length()<=size_total) {
							if(file_dest.length()==size_total){
								bool=false;
							}
							size_copy=file_dest.length();
							//进度
							int percent_process_now = (int) (size_copy*100/size_total);
							if (percent_process!=percent_process_now) {
								if (size_total==size_copy) {
									//开始按钮可以点击
									confirm.setEnabled(true);
								}
								percent_process=percent_process_now;
								jbar.setValue(percent_process); // 随着线程进行,增加进度条值
								jbar.setString(percent_process+"%");
							}
						}else {
							bool=false;
						}
					}
					
				}
			}).start();
			
		}
	}
	/**
	 * 递归复制
	 * @param file_src
	 * @param directory_dest
	 * @throws IOException
	 */
	public static void copyRecursive(File file_src,File directory_dest) throws IOException{
		if (file_src.exists()&&directory_dest.exists()&&directory_dest.isDirectory()) {
			if (file_src.isDirectory()) {
				File directory_dest2 = new File(directory_dest, file_src.getName());
				directory_dest2.mkdirs();
				File[]files = file_src.listFiles();
				for (File file : files) {
					copyRecursive(file, directory_dest2);
				}
			}else {
				File file_dest = new File(directory_dest,file_src.getName());
//				System.out.println(file_src.getAbsolutePath());
//				System.out.println(file_dest.getAbsolutePath());
				if (file_src.length()<1024*1024*100) {
					copyChannel(file_src, file_dest);
				}else {
					copyBigFile(file_src, file_dest);
				}
				size_copy += file_src.length();
				
				if (size_copy<=size_total) {
					//进度
					int percent_process_now = (int) (size_copy*100/size_total);
					if (percent_process!=percent_process_now) {
						if (size_total==size_copy&&percent_process_now==100) {
							//开始按钮可以点击
							confirm.setEnabled(true);
						}
						percent_process=percent_process_now;
						jbar.setValue(percent_process); // 随着线程进行,增加进度条值
						jbar.setString(percent_process+"%");
					}
				}
//				System.out.println(size_copy+"--"+size_total);
			}
		}
	}
	/**
	 * 递归删除
	 * @param file_src
	 * @param directory_dest
	 * @throws IOException
	 */
	public static void deleteRecursive(File file) throws IOException{
		if (file.exists()) {
			if (file.isDirectory()) {
				File[]files = file.listFiles();
				for (File f : files) {
					deleteRecursive(f);
				}
				file.delete();
			}else {
				file.delete();
			}
		}
	}
	public static void getFileSize(File file) throws IOException{
		if (file.exists()&&file.isDirectory()) {
			File[]files = file.listFiles();
			for (File f : files) {
				if (f.isDirectory()) {
					getFileSize(f);
				}else {
					size_total += f.length();
				}
			}
		}else {
			size_total += file.length();
		}
	}
	/**
	 * 复制大文件,1G+
	 * @param src
	 * @param dest
	 */
	public static void copyBigFile(File src, File dest) {
		FileInputStream fin = null;
		FileOutputStream fout = null;
		FileChannel in = null;
	    FileChannel out = null;
		try {
			//缓冲区--设置了100m
			ByteBuffer byteBuf = ByteBuffer.allocate(1024*1024*100);
			
			fin = new FileInputStream(src);
			fout = new FileOutputStream(dest);
			in = fin.getChannel();
		    out = fout.getChannel();
		    
		    while (true) {
				int eof = in.read(byteBuf);
				if (eof == -1)
					break;
				byteBuf.flip();
				out.write(byteBuf);
				byteBuf.clear();
			}
		    
			in.close();
			out.close();
			fin.close();
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in!=null) {
					in.close();
				}
				if (out!=null) {
					out.close();
				}
				if (fin!=null) {
					fin.close();
				}
				if (fout!=null) {
					fout.close();
				}
			} catch (Exception e2) {
//				e2.printStackTrace();
			}
		}
	}
	//管道复制
	public static void copyChannel(File src,File dest){
		FileInputStream fin = null;
		FileOutputStream fout = null;
		FileChannel in = null;
	    FileChannel out = null;
		try {
			fin = new FileInputStream(src);
			fout = new FileOutputStream(dest);
			in = fin.getChannel();
		    out = fout.getChannel();
		    in.transferTo(0, in.size(), out);
			in.close();
			out.close();
			fin.close();
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in!=null) {
					in.close();
				}
				if (out!=null) {
					out.close();
				}
				if (fin!=null) {
					fin.close();
				}
				if (fout!=null) {
					fout.close();
				}
			} catch (Exception e2) {
//				e2.printStackTrace();
			}
		}
	}
	public static void copy(File src,File dest){
		try {
			InputStream in = new FileInputStream(src);
			OutputStream out = new FileOutputStream(dest);
			int c = -1;
			while ((c=in.read())!=-1) {
				out.write(c);
			}
			in.close();
			out.close();
		} catch (Exception e) {
//			e.printStackTrace();
		}
	}
	private static TextField TEXT_FROM = null;
	private static TextField TEXT_TO = null;
	private static String PATH_FROM = "";
	private static String PATH_TO = "";

	
	/**
	 * 弹出选择框返回选中文件夹或者文件的路径
	 * @param type:1只文件2只文件夹3文件和文件夹
	 * @return
	 */
	public static String openFile(int type) {
		JFrame frame = new JFrame();
		String filename = File.separator + "temp";
		File f = new File(filename);
		JFileChooser fc = new JFileChooser(f);
		int mode = JFileChooser.FILES_AND_DIRECTORIES;
		if (type==1) {
			mode = JFileChooser.FILES_ONLY;
		}else if (type==2) {
			mode = JFileChooser.DIRECTORIES_ONLY;
		}else {
			
		}
		fc.setFileSelectionMode(mode);
		int result = fc.showOpenDialog(frame);
		if (result == 0) {
			File selFile = fc.getSelectedFile();
			return selFile.toString();
		}
		return "";
	}
	
	public static void main(String[] args) {
		JFrame jf = new JFrame("光速复制");
		jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
		jf.setLocation(390, 200);
		jf.setSize(600, 320);
		jf.setResizable(false);
		
		Container p  = jf.getContentPane();
		p.setLayout(null);
		
		//文字
		JLabel label_start = new JLabel("复制");
		label_start.setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
		label_start.setBounds(50, 50, 80, 30);
		p.add(label_start);
		JLabel label_end = new JLabel("到");
		label_end.setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
		label_end.setBounds(50, 100, 80, 30);
		p.add(label_end);
		// 组件
		TEXT_FROM = new TextField("", 10);
		TEXT_FROM.setBounds(150, 50, 220, 30);
		TEXT_FROM.setEnabled(false);
		p.add(TEXT_FROM);
		TEXT_TO = new TextField("", 10);
		TEXT_TO.setBounds(150, 100, 220, 30);
		TEXT_TO.setEnabled(false);
		p.add(TEXT_TO);

		//from 浏览
		JButton b = new JButton("浏览...");
		b.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
		b.setBackground(Color.white);
		b.setBounds(420, 50, 80, 30);
		b.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				try {
					PATH_FROM = openFile(3);
					TEXT_FROM.setText(PATH_FROM);
					//统计文件总大小
					size_total=0;
					getFileSize(new File(PATH_FROM));
					String text_totalsize = "约"+toUnit(size_total);
					label_jbar.setText(text_totalsize);
					jbar.setValue(0);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		p.add(b);
		//to 浏览
		JButton c = new JButton("浏览...");
		c.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
		c.setBackground(Color.white);
		c.setBounds(420, 100, 80, 30);
		c.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				
				PATH_TO = openFile(2);
				TEXT_TO.setText(PATH_TO);
			}
		});
		p.add(c);
		
		//进度条
		jbar = new JProgressBar(0,100);
		jbar.setBounds(50, 160, 500, 20);
		jbar.setValue(0);
		jbar.setMinimum(0);
		jbar.setMaximum(100);
		jbar.setStringPainted(true);
		jbar.addChangeListener(new ChangeListener() {
			
			public void stateChanged(ChangeEvent e) {
				
			}
		});
		p.add(jbar);
		
		//耗时&速度
		label_result = new JLabel();
		label_result.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
		label_result.setBounds(50, 180, 150, 30);
//		label_result.setText("耗时20秒,10M/s");
		p.add(label_result);
		//进度条文字
		label_jbar = new JLabel();
		label_jbar.setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
		label_jbar.setBounds(450, 180, 80, 30);
		p.add(label_jbar);
		
		//
		confirm = new JButton("开始");
		confirm.setBackground(Color.white);
		confirm.setFont(new Font("SimSun", Font.BOLD, 18));
		confirm.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				final File file_from = new File(PATH_FROM);
				final File file_to = new File(PATH_TO);
				if (!file_from.exists()) {
					
					return ;
				}
				if (!file_to.exists()) {
					
					return ;
				}
				//进度归零
				jbar.setValue(0);
				jbar.setString("0%");
				size_copy = 0;
				percent_process = 0;//进度百分比
				label_result.setText("");
				
				String path = file_to.getAbsolutePath()+File.separator+file_from.getName();
				System.out.println(path);
				File file_exist = new File(path);
				try {
					deleteRecursive(file_exist);
				} catch (IOException e2) {
					e2.printStackTrace();
				}
				System.out.println(file_exist.exists());
				//因为事件监听的原因,必须开启新的线程,否则将等待此程序执行完以后才能执行其他的线程
				new Thread(new Runnable() {
					
					public void run() {
						try {
							if (file_from.isDirectory()) {
								long s = System.currentTimeMillis(); 
								copyRecursive(file_from,file_to);
								long e = System.currentTimeMillis(); 
								long a = (e-s)/1000;
								long b = size_total/(1024*1024);
								long c = new Double(b/a).longValue();
								label_result.setText("耗时"+a+"秒,"+c+"M/s");
							}else {
								copyOne(file_from, file_to);
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}).start();
				//开始按钮不可点击
				confirm.setEnabled(false);
			}
		});
		confirm.setBounds(350, 220, 100, 40);
		p.add(confirm);
		//
		JButton cancel = new JButton("关闭");
		cancel.setBackground(Color.white);
		cancel.setFont(new Font("SimSun", Font.BOLD, 18));
		cancel.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		cancel.setBounds(100, 220, 100, 40);
		p.add(cancel);
		
		p.setBounds(100, 50, 300, 200);
		
		jf.setVisible(true);
		
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值