【问题标题】:Java file copy to non empty destination folderJava 文件复制到非空目标文件夹
【发布时间】:2020-09-16 16:27:10
【问题描述】:

在不使用 FileUtils 导入的情况下,我很难弄清楚如何对其进行编码。我找到了数千个关于如何将文件移动到空文件夹的教程,这很容易。困难在于找出 Java 如何将文件移动到文件夹中已有文件的目录。据我了解,REPLACE_EXISTING 参数意味着如果在目标目录中检测到相同的文件名,它将覆盖相同的文件名,但该目录没有与我尝试复制/移动的文件的名称匹配的文件。我错过了什么?我怎样才能做到这一点?

java.nio.file.DirectoryNotEmptyException 发生。

enter code here

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;



public class Move {
 static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");


public static void move(File src, File dest) throws IOException {
    Files.move(src.toPath().toAbsolutePath(), dest.toPath().toAbsolutePath(),
            StandardCopyOption.REPLACE_EXISTING);         
}

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

try {       
    if(source.isDirectory() && destination.isDirectory()) {         
        File[] content = source.listFiles();           
        for(int i = 0; i < content.length; i++) {
            System.out.println(content[i]);  
            move(source, destination);                
        }            
    }
    else if (!destination.isDirectory()){ 
        System.out.println("create folder here");
        destination.mkdir();
        File[] content = source.listFiles();           
        for(int i = 0; i < content.length; i++) {
            move(source, destination);              
        }
    }
 }
 catch(Exception ex) {   System.out.println(ex);    
 }
 finally {
    
 }
 }
 }

【问题讨论】:

  • 如果您知道目标目录没有与您正在复制/移动的源文件名称匹配的任何文件,则不存在冲突,并且目标目录也可能被认为是空的。我不明白你认为的问题是什么。你到底想在这里问什么?
  • 如果目录已经有一个同名的文件,你怎么再把另一个同名的文件放在那里呢?我建议您添加另一个 IF 分支并进行检查:如果存在具有此类名称的文件-您将新文件的名称更改为其他值。如果不是 -> 你正常复制文件。
  • 告诉我是否正确理解了您的意图,我会为您提供一段代码,在循环中添加索引后缀,直到文件名唯一。
  • 请试试这个片段。它没有 FileUtils private static void copy(File src, File dest) throws IOException { try (InputStream is = new FileInputStream(src); OutputStream os new FileOutputStream(dest) { // buffer size 1K byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buf)) &gt; 0) { os.write(buf, 0, bytesRead); } } }
  • REPLACE_EXISTING 不要求存在同名的现有文件。使用 REPLACE_EXISTING 意味着如果存在同名文件,它应该被覆盖。如果不存在同名文件,则忽略 REPLACE_EXISTING。

标签: java file path move


【解决方案1】:

我尝试了带有参数 StandardCopyOption.REPLACE_EXISTING 的 IDE File.move 方法中的代码,仅当目标文件夹中有文件时才有效。否则使用 File.move 正常方式。为了避免代码重复,我还稍微修改了您的代码。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;

public class Move {
    static File source = new File("sourcefolderhere");
    static File destination = new File("destfolderhere");

    public static void move(File src, File dest) throws IOException {
        System.out.println(src.getName());
        if(isExist(src.getName()))
            Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()) , StandardCopyOption.REPLACE_EXISTING);
        else
            Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()));
    }
    
    public static boolean isExist(String souceFileName){
        //If you are not using java 8 code
        /*String[] destFiles = destination.list();
        for(String fileName : destFiles){
            if(souceFileName.equals(fileName))
                return true;
        }
        return false;*/
        return Arrays.stream(destination.list())
                .anyMatch(fileName -> fileName.equals(souceFileName));
    }

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

        try {
            if(!source.isDirectory())
                throw new IllegalArgumentException("Source Folder doesn't Exist");
            if(!destination.exists())
                destination.mkdir();
            if (source.isDirectory() && destination.isDirectory()) {
                File[] content = source.listFiles();
                for (int i = 0; i < content.length; i++) {
                    System.out.println(content[i]);
                    move(content[i], destination);
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        } finally {

        }
    }
}```

【讨论】:

  • 谢谢。我试过了,它仍然没有将文件复制到已经有内容的目录中。我仍然得到 file.DirectoryNotEmptyException
  • 我尝试了以下场景。 destfldr -> file1.txt sourcefldr -> file1.txt,file2.txt。结果是 destfldr -> file1.txt、file2.txt 和 sourcefldr -> nofile。这个对我有用!文件移动是递归的吗?意思是它有嵌套的文件夹可以移动吗?
  • 就是这样,我不是手动输入文件名,而是遍历每个文件的文件夹。名字变了,我不知道新名字会是什么。
  • 你能给我举个例子,包括源和目标的文件和文件夹
  • 我不使用单个文件。静态文件源 = new File("\\\\server\folder\folder");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多