Java文件复制失败

时间:2019-07-05 13:00:42

标签: java

我编写了一个非常简单的Java程序,将作为参数传递的文件复制到/ tmp目录。该程序会产生一些Java异常。

public class CopyFile {
public static void main(String[] args) throws IOException {
    String fqp2File = "";

    if (new File(args[0]).isFile()) {
       fqp2File = args[0];
    }
    else {
       System.out.println("Passed argument is not a file");
    }
    copy(fqp2File, "/tmp");
}

private static boolean copy(String from, String to) throws IOException{
    Path src = Paths.get(from);
    Path dest = Paths.get(to);
    try {
        Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
        return true;
    } catch (IOException ioe) {
        System.err.format("I/O Error when copying file");
        ioe.printStackTrace();
        return false;
    }
}

}

运行此程序时出现以下错误:

java -jar CopyFile.jar /home/downloads/dfA485MVSZ.ncr.pwgsc.gc.ca.1531160874.13500750
I/O Error when copying filejava.nio.file.FileSystemException: /tmp:
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:103)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:114)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:119)
        at sun.nio.fs.UnixCopyFile.copy(UnixCopyFile.java:578)
        at  sun.nio.fs.UnixFileSystemProvider.copy(UnixFileSystemProvider.java:265)
        at java.nio.file.Files.copy(Files.java:1285)
        at ca.gc.ssc.gems.esnap.cipo.CopyFile.copy(CopyFile.java:39)
        at ca.gc.ssc.gems.esnap.cipo.CopyFile.main(CopyFile.java:31)

1 个答案:

答案 0 :(得分:2)

为了测试您的代码,我使用C:/tmp/test.txt;作为您的args[0]。我通过为输出指定文件名来解决此问题,如下所示:

Path dest = Paths.get(to);

Path dest = Paths.get(to, "test2.txt");

现在它已成功将文件复制到该名称,您可以根据需要修改文件名,或添加逻辑以自动更改文件名。