java实现文件的移动(剪切)

package javaio.recursion.Reader;

import java.io.*;
import java.util.Scanner;

public class FileCut {

	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		System.out.println("输入你想要剪切的文件或文件夹");
		String str1=s.next();
		System.out.println("输入你想要粘贴在哪de文件夹");
		String str2=s.next();
		File f1=new File(str1);
		File f2=new File(str2);
		filecut(f1,f2);

	}
	
	public static void filecut(File fs,File ft) {
		/*if(fs.isFile()&&ft.isDirectory()) {
			File tmp=ft;
			File f=new File(ft,fs.getName());
			if(!fs.renameTo(f)) {
				ft=new File(tmp,ft.getName()+"-副本");
				fs.renameTo(f);
			}
		} */if(ft.isDirectory()) {

			File tmp=ft;
			ft=new File(ft,fs.getName());
			if(!ft.mkdirs()) {
				ft=new File(tmp,fs.getName()+"-副本");  //如果是相同的文件名 即目录创建失败 则改名
				ft.mkdirs();
			}
			File []file=fs.listFiles();
			for(File x:file) {
				if(x.isDirectory()) {
				  //File f=new File(ft,x.getName());
                  //System.out.println(x.getAbsolutePath());
                  //System.out.println(f.getAbsolutePath());
					filecut(x,ft);
				}else {
					File f=new File(ft,x.getName());
					x.renameTo(f);
				}
			}
			deletedir(fs);
			
		}
	}
	public static void deletedir(File f) {
		if(!f.exists())
		{
			System.out.println("文件不存在");
		}else
		{
			if(f.delete())
			{
				System.out.println("删除:"+f.getName());
			}else
			{
				File[] f1=f.listFiles();
				for(File x:f1) {
					deletedir(x);
				}
				deletedir(f);
			}
		}
	}

}
posted @ 2024-08-17 02:10  Reisen7  阅读(125)  评论(0)    收藏  举报  来源