【问题标题】:Copying a file.Finding a path to it复制文件。找到它的路径
【发布时间】:2014-08-16 16:00:01
【问题描述】:

我想将文件复制到另一个目录。我知道这已被问过数百万次,我阅读了大量关于此的答案,但我似乎无法让它工作。这是我目前使用的代码:

copyFile(new File(getClass().getResource("/jars/TurnOffClient.jar").toString()),
   new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));

这就是方法:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

这是我的目录: Directories http://imageshack.com/a/img820/6418/5g3m.png

/////////////////////////////////////// //////////////////////////////////// 这是我得到的例外:

【问题讨论】:

  • 你认为getClass().getResource("/jars/TurnOffClient.jar") 做了什么,为什么?
  • 这里的问题是独一无二的,因为他试图从 JAR 中复制文件。
  • getClass 获取类在机器中的路径?

标签: java file url jar path


【解决方案1】:

您是否尝试过使用 java.nio.Files.copy(); ? 有内置的方法可以做到这一点。

如果这不起作用,那么继续将字节从文件输入流传输到输出文件流。

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

如此处所述:Standard concise way to copy a file in Java?

【讨论】:

    【解决方案2】:

    复制文件的标准方法不起作用,因为您试图将文件复制出 JAR。当您从 JAR 中获取文件时,您无法为其获取 File 对象。你可以得到一个URL,并从中得到一个InputStream

    现有答案包括将数据从一个输入流复制到另一个输入流的代码。在这里,适用于 JAR 中的文件:

    InputStream in = getClass().getResourceAsStream("/jars/TurnOffClient.jar");
    OutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
    
    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
    

    【讨论】:

    • 您的 while 循环确实应该与 -1 (EOF) 进行比较
    猜你喜欢
    • 2022-10-17
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多