使用Java将文件从父目录移动到子目录

huangapple go评论143阅读模式
英文:

Move files from parent to subdirectory using java

问题

以下是代码的翻译部分:

public static void main(String[] args) throws IOException {

     String path = "Workspace/MainFolder/";
    String targetPath="Workspace/Dest/";
    Files.walk(Paths.get(path), 5).forEach(p -> {
        if (p.toFile().isDirectory()) {
            Stream.of(new File(path).listFiles()).filter(File::isFile).map(f -> new File(f.getPath().replace(path, targetPath))).forEach(f -> {
                f.getParentFile().mkdirs();
                try {
                    Files.copy(p, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    // 处理异常
                    e.printStackTrace();
                }
            });
        } else {
            try {
                Files.copy(p, new File(p.toFile().getPath().replace(path, targetPath)).toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                // 处理异常
                e.printStackTrace();
            }
        }
    });
}

请注意,我已经删除了HTML编码的引号,以便代码更容易阅读。

英文:

Hi I am trying to copy the files and folders from root folder to subfolders which are upto level 5.It has to work same if the folders or files need to added.

I have tried some examples regarding level parametric and able to list directories and Suggest me the approach to get the output folder,files structure.

public static void main(String[] args) throws IOException {

     String path = "Workspace/MainFolder/";
    String targetPath="/Workspace/Dest/";
    Files.walk(Paths.get(path),5).forEach(p->{
        if(p.toFile().isDirectory()){
            Stream.of(new File(path).listFiles()).filter(File::isFile).map(f->new File(f.getPath().replace(path,targetPath))).forEach(f->{
                f.getParentFile().mkdirs();
                try {
					Files.copy(p,f.toPath(),StandardCopyOption.REPLACE_EXISTING);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            });
        }else{
            try {
				Files.copy(p,new File(p.toFile().getPath().replace(path,targetPath)).toPath(),StandardCopyOption.REPLACE_EXISTING);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    });
  }
 }

答案1

得分: 2

以下是代码的翻译部分:

package q63242312;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

public class RecCopyWithRoot {

	private static boolean deleteDirectory(File directoryToBeDeleted) {
		File[] allContents = directoryToBeDeleted.listFiles();
		if (allContents != null) {
			for (File file : allContents) {
				deleteDirectory(file);
			}
		}
		return directoryToBeDeleted.delete();
	}

	public static void main(String[] args) {
		String from = "./from";
		String to = "./to";
		try {
			File srcFile = new File(from).toPath().toAbsolutePath().toFile();
			File targetFile = new File(to).toPath().toAbsolutePath().toFile();
			if (!deleteDirectory(targetFile)) {
				//throw new IllegalStateException("cannot delete output directory");
			}
			copyFolder(srcFile.toPath(), targetFile.toPath());
			
			try (Stream<Path> stream = Files.walk(srcFile.toPath(), 5)) {
				stream.filter(p -> p.toFile().isDirectory()).forEach(dir -> {	
					Path tmpDir = dir;
					//System.err.println(tmpDir);
					while ((tmpDir = tmpDir.getParent()).toFile().getAbsolutePath().startsWith(srcFile.getAbsolutePath())) {//TODO while has parent
						
						for (File f : tmpDir.toFile().listFiles()) {//TODO srcFile.listFiles() --> all from root to dir
							if (f.isFile()) {
								System.out.println("res: " + dir + " | " + srcFile + " | " + f);
								System.out.println(f.getName() + " --> " + targetFile.toPath().resolve(srcFile.toPath().relativize(f.toPath())));
								try {
									Files.copy(f.toPath(), new File(targetFile.toPath().resolve(srcFile.toPath().relativize(dir)).toFile(), f.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}
					
				});
			}
			for (File toDelete: targetFile.listFiles()) {
				toDelete.delete();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void copyFolder(Path src, Path dest) throws IOException {
		System.out.println(src + "-->" + dest);
		if (src.toFile().isDirectory()) {
			try (Stream<Path> stream = Files.walk(src)) {
				stream.forEach(source -> {
					Path newDest = dest.resolve(src.relativize(source));
					if (!newDest.toFile().exists()) {
						try {
							Files.copy(source, newDest, StandardCopyOption.REPLACE_EXISTING);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				});
			}
		} else {
			//Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
		}

	}
}
英文:

What about this solution?

package q63242312;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

public class RecCopyWithRoot {

	private static boolean deleteDirectory(File directoryToBeDeleted) {
		File[] allContents = directoryToBeDeleted.listFiles();
		if (allContents != null) {
			for (File file : allContents) {
				deleteDirectory(file);
			}
		}
		return directoryToBeDeleted.delete();
	}

	public static void main(String[] args) {
		String from = &quot;./from&quot;;
		String to = &quot;./to&quot;;
		try {
			File srcFile = new File(from).toPath().toAbsolutePath().toFile();
			File targetFile = new File(to).toPath().toAbsolutePath().toFile();
			if (!deleteDirectory(targetFile)) {
				//throw new IllegalStateException(&quot;cannot delete output directory&quot;);
			}
			copyFolder(srcFile.toPath(), targetFile.toPath());
			
			try (Stream&lt;Path&gt; stream = Files.walk(srcFile.toPath(), 5)) {
				stream.filter(p -&gt; p.toFile().isDirectory()).forEach(dir -&gt; {	
					Path tmpDir=dir;
					//System.err.println(tmpDir);
					while((tmpDir=tmpDir.getParent()).toFile().getAbsolutePath().startsWith(srcFile.getAbsolutePath())) {//TODO while has parent
						
						for (File f : tmpDir.toFile().listFiles()) {//TODO srcFile.listFiles() --&gt; all from root to dir
							if(f.isFile()) {
								System.out.println(&quot;res: &quot;+dir+&quot; | &quot;+srcFile+&quot; | &quot;+f);
								System.out.println(f.getName()+&quot; --&gt; &quot;+targetFile.toPath().resolve(srcFile.toPath().relativize(f.toPath())));
								try {
									Files.copy(f.toPath(), new File(targetFile.toPath().resolve(srcFile.toPath().relativize(dir)).toFile(), f.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}
					
				});
			}
			for (File toDelete: targetFile.listFiles()) {
				toDelete.delete();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void copyFolder(Path src, Path dest) throws IOException {
		System.out.println(src + &quot;--&gt;&quot; + dest);
		if (src.toFile().isDirectory()) {
			try (Stream&lt;Path&gt; stream = Files.walk(src)) {
				stream.forEach(source -&gt; {
					Path newDest = dest.resolve(src.relativize(source));
					if (!newDest.toFile().exists()) {
						try {
							Files.copy(source, newDest, StandardCopyOption.REPLACE_EXISTING);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				});
			}
		} else {
			//Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
		}

	}
}

huangapple
  • 本文由 发表于 2020年8月4日 15:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63242312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定