java定时复制文件夹及文件,可视化界面(递归)

java定时复制文件夹及文件,可视化界面(递归)

package swing;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
/**
 * 文件夹定时复制
 * @author CQ
 *
 */
public class FileCopy extends Frame implements ActionListener{

	private static final long serialVersionUID = 1L;
//	 private static String IP = "10.126.252.68";  
//	    private static int PORT = 22;  
//	    private static String USER = "test";//  远程Linux服务器的用户名 
//	    private static String PASSWORD = "teller";// 远程Linux服务器的登录密码
//	    private static Connection connection = new Connection(IP, PORT);  
//	    private static boolean usePassword = true;// 使用用户名和密码来进行登录验证
	
	
	/**
	 * 窗口设置 
	 */
	public int rate = 0;
	String oldFilepath;
	String newFilepath;
	//进程条
	private JProgressBar pro =  new JProgressBar();
	JPanel frame;
	Button copy = new Button("Copy");
	JTextArea FromPath = new JTextArea("");
	JTextArea ToPath = new JTextArea("");
	
	Run A = new Run();
	FileCopy(){
		
		frame = new JPanel();
		frame.setLayout(null);
		
		final JLabel j1 = new JLabel("此地址开始复制:");
		final JLabel j2 = new JLabel("复制至此地址中:");
		
		//设置x,y,width,height
		j1.setBounds(0, 0, 100, 100);
		FromPath.setBounds(100, 40, 300, 40);
		j2.setBounds(0, 100, 100, 100);
		ToPath.setBounds(100, 140, 300, 40);
		copy.setBounds(400, 100, 80, 40);
		pro.setBounds(50, 200, 400, 40);
		
		
		//进程条设置背景颜色pro.setBackground(Color.GREEN)
		pro.setStringPainted(true);
		
		copy.addActionListener(this);
		
		frame.add(j1);
		frame.add(FromPath);
		frame.add(ToPath);
		frame.add(j2);
		frame.add(copy);
		frame.add(pro);
		this.add(frame);
		
		A.start();
		
	}
	
	/**
	 * 文件或文件夹批量复制方法,使用递归。
	 * @param sourcePath 源文件绝对路径
	 * @param destPath 目标文件夹绝对路径
	 */
	public void copy(String sourcePath, String destPath){
		try {
//			 Process process = Runtime.getRuntime().exec(
//                     "cmd.exe /c pscp -r -l "+username()
//                     +" -pw "+password+" -P "+port+" "
//                     +ip+":"+remotePath+" "+targetPath);
//             BufferedReader bufferedReader = new BufferedReader(
//                     new InputStreamReader(process.getInputStream()));
//             BufferedReader errReader = new BufferedReader(
//                     new InputStreamReader(process.getErrorStream()));
//             while ((err = errReader.readLine()) != null)
//                     System.out.println(err);
//             while ((str = bufferedReader.readLine()) != null)
//                     System.out.println(str);
//             process.destroy();
			
			File oldFile = new File(sourcePath);
			File newFile = new File(destPath);
			 if(!oldFile.exists()){
		            System.out.println("请检查您的源路径是否合法!");
		        }
//			    String oldSrcName = oldFile.getName();
//	            File newSrcDir = new File(newFile, oldSrcName);
//	            newSrcDir.mkdirs();

				//获取目录下所有文件
		        File[] listFiles = oldFile.listFiles();
//		        for(File f : listFiles){
//		            System.out.println(f.getName());
//		            if(f.isDirectory()){
//		                //递归
		                System.out.println(f+"--------->"+destPath+"\\"+f.getName());
//		            	copy(oldFile+"\\"+f.getName(),newFile+"\\"+f.getName());
//		            }else if(f.isFile()){
//		            	//递归
		            	System.out.println(f+"--------->"+destPath+"\\"+f.getName());
//		            	CopyDocuments.copyDocuments(oldFile+"\\"+f.getName(),newFile+"\\"+f.getName());
//		            }
//		        }
		        for(File f : listFiles) {
		        	System.out.println(f.getName());
		        	if(f.isFile()) {
		        		//递归
		        		CopyDocuments.copyDocuments(f.getPath(),newFile.getPath());
		        	}else if(f.isDirectory()) {
		        		//递归
		        		File nextFile = new File(newFile.getPath() + File.separator + f.getName());
		        		nextFile.mkdir();
		        		copy(oldFile+"\\"+f.getName(),newFile+"\\"+f.getName());
		        	}
		        	
		        }
		}catch (Exception e) {
			System.out.println("文件复制发生错误!" + e);
		}
	}
	
	
	/**
	 * 动作监听器
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == copy) {
			oldFilepath = FromPath.getText();
			newFilepath = ToPath.getText();
			System.out.println(oldFilepath);
			System.out.println(newFilepath);
		}
	} 
	
	
	/**
	 * 设定毫秒运行的线程
	 * @author IT
	 *
	 */
	private class Run extends Thread {
		public void run() {
			//文件复制测试
//			String oldFilepath = "D:/2.txt";
//			String newFilepath = "D:/2/2.txt";
			while(true) {
				System.out.println("启动...");
				if(oldFilepath!=null) {
					try {
						copy(oldFilepath, newFilepath);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				try{
					Thread.sleep(200000);//1秒1000毫秒,一天86400000毫秒
				}catch(Exception e) {
					System.out.println(e);
				}
			}
		}
	}
	
	
	public static void main(String[] args) {
		FileCopy copy = new FileCopy();
		
		//窗口关闭,系统退出或关闭
		copy.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		
		
		//窗口设置
		copy.setBounds(0,0,500,300);
		copy.setVisible(true);
		copy.setLayout(null);
		copy.setResizable(false);
		
	}
	

}

文件复制

package swing;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 文件复制
 * @author CQ
 *
 */
public class CopyDocuments {

	public static void main(String[] args) throws Exception {
		 copyDocuments("E:\\2","E:\\1");
	}
	/**
	 * 复制文件
     * 从源路径到目标文件夹路径,文件名保持一致
     * 如果目标文件夹不存在则自动创建
     * 如果文件已经存在则自动编号-copy n
     * 
	 * @param SourcePath 源文件绝对路径
	 * @param DestPath 目标文件夹绝对路径
	 * @return 是否复制成功
	 * @throws IOException 
	 */
	@SuppressWarnings("resource")
	public static boolean copyDocuments(String SourcePath, String DestPath)  {
		 File oldFile = new File(SourcePath);
		 File newFile = new File(DestPath);
		
		 if (!oldFile.exists() || oldFile.isDirectory()) {
	            return false;
	        }
	     if (!newFile.exists()) {
	    	 newFile.mkdirs();
	        }
	        String oldFileName = oldFile.getName();	
	        Pattern suffixPattern = Pattern.compile("\\.\\w+");
	        Matcher matcher = suffixPattern.matcher(oldFileName);
	        String nameBody;
	        String suffix;
	        if (matcher.find()) {
	            nameBody = oldFileName.substring(0, matcher.start());
	            suffix = oldFileName.substring(matcher.start());
	        } else {
	            nameBody = oldFileName;
	            suffix = "";
	        }
	        int fileNumber = 0;
	        File newFile1 = new File(DestPath, oldFileName);
	        while (newFile1.exists()) {
	            fileNumber++;
	            String newFileName = nameBody + "-copy" + fileNumber + suffix;
	            newFile1 = new File(newFile1, newFileName);
	        }
	        try {
	            FileChannel fileIn = new FileInputStream(oldFile).getChannel();
				FileChannel fileOut = new FileOutputStream(newFile1).getChannel();
	            fileIn.transferTo(0, fileIn.size(), fileOut);
	            fileIn.close();
	            fileOut.close();
	        } catch (IOException e) {
	            return false;
	        }
	        return true;
	    }
//	    File oldFile = new File(SourcePath);
//		File newFile = new File(DestPath);
//		 if(!oldFile.exists() || oldFile.isDirectory()){
//			 System.out.println("错误");
//	        }
//		 if(!newFile.exists()){
//			 newFile.mkdirs();
//	            System.out.println("创建文件夹!");
//	        }
//      //读入文件到程序高级流
//      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(SourcePath));
//      //写入数据到文件高级流
//      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(DestPath));
//      byte[] b = new byte[1024];
//      int len = 0;
//      while((len = bis.read(b)) != -1){
//          bos.write(b, 0, len);
//      }
//      bis.close();
//      bos.close();
//      System.out.println("复制文件完成!");
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
MD5校验码:f4f9ea3f7bcc3375192be61dc110cb58 1、本软件是定时自动备份软件。 2、备份任务自动拷贝文件文件大小或修改时间变化的文件 3、MyCopy.exe是配置界面,该文件生成配置文件mycopy.ini,并能显示系统运行状态。 4、MyCopyTask.exe是执行拷贝任务的程序,它根据mycopy.ini配置的信息定时进行拷贝,在休眠状态下每5秒钟检查一次是否到达任务指定的拷贝时间。拷贝过程中出现错误,记录log.ini文件,但不会终止拷贝进程。 5、MyCopy.exe配置界面里有“启动”按钮把运行状态改为“运行”,并启动MyCopyTask.exe程序;“终止”按钮把运行状态改为“终止”,MyCopyTask.exe检测到系统状态时为“终止”则自动退出。“退出”按钮退出配置界面,但不会终止MyCopyTask.exe程序。“暂停”也会推出MyCopyTask.exe程序,但下次启动时,从上次暂停的任务开始继续拷贝。 6、MyCopyTask.exe运行时托盘上会显示图标。 7、要实现拷贝任务的自动启动,可以把MyCopyTask.exe加入到windows系统的“启动”菜单中,但配置文件中的运行状态一定是“启动”,否则程序会自动退出。 8、程序拷贝文件时意外终止,可以坚持mycopy.ini文件中的[系统状态]是否有“半个文件”,如果有说明“运行信息”中包含的文件没有拷贝完整。 9、如果因为某种原因错过了任务执行时机的话,拷贝程序会在启动后补回错过的拷贝任务。 10、任务名和文件路径中不能出现","(半角逗号) 11、标准版只记录log.ini文件,健康提示版当任务执行完之后会弹出提示信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值