【问题标题】:Copying file using Apache Commons FileUtils使用 Apache Commons FileUtils 复制文件
【发布时间】:2019-04-30 02:24:16
【问题描述】:

在第一次运行时,我想将给定的File 复制到具有新文件名的新位置。

每次后续运行都应覆盖第一次运行时创建的相同目标文件。

第一次运行时,目标文件不存在。只有目录存在。

我写了以下程序:

package myTest;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;

import org.apache.commons.io.FileUtils;

public class FileCopy {

    public static void main(String[] args) {
        TestFileCopy fileCopy = new TestFileCopy();
        File sourceFile = new File("myFile.txt");
        fileCopy.saveFile(sourceFile);
        File newSourceFile = new File("myFile_Another.txt");
        fileCopy.saveFile(newSourceFile);
    }
}

class TestFileCopy {
    private static final String DEST_FILE_PATH = "someDir/";
    private static final String DEST_FILE_NAME = "myFileCopied.txt";

    public void saveFile(File sourceFile) {
        URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
                + DEST_FILE_NAME);
        try {
            File destFile = Paths.get(destFileUrl.toURI()).toFile();
            FileUtils.copyFile(sourceFile, destFile);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

但是,这会在以下行引发空指针异常:

File destFile = Paths.get(destFileUrl.toURI()).toFile();

我错过了什么? 目录someDir 直接在我项目在eclipse 的根目录下。 源文件myFile.txtmyFile_Another.txt 都直接存在于eclipse 中我项目的根目录下。

【问题讨论】:

    标签: java file apache-commons


    【解决方案1】:

    我使用了它,它按我的预期工作:

    public void saveFile1(File sourceFile) throws IOException {
            Path from = sourceFile.toPath();
            Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
            Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
        }
    

    使用 Java nio

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      相关资源
      最近更新 更多