代码之家  ›  专栏  ›  技术社区  ›  Vicky

使用apachecommons FileUtils复制文件

  •  0
  • Vicky  · 技术社区  · 7 年前

    在第一次运行时,我想复制给定的 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.txt myFile_Another.txt 存在于eclipse中我项目的根目录下。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Vicky    7 年前

    我用了这个,它的效果和我预期的一样:

    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

    推荐文章