java - 复制文件。查找它的路径

标签 java file url jar path

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

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

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 这是我得到的异常(exception): Exception

最佳答案

复制文件的标准方法不起作用,因为您正在尝试将文件从 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();

关于java - 复制文件。查找它的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24419685/

相关文章:

java - 如何使用elasticsearch java api连接位于不同服务器上的多个节点?

java - 圆的 3D 旋转使边缘交叉两点

c++ - 输出文本文件的位置

c# - 安全地将变量值从一个页面传递到另一个页面

python - URL : Binary Blob, Unicode 或编码的 Unicode 字符串?

java - 如何使用 BufferedReader 将 String 添加到 ArrayList 中?

java - 如何使用JAVA在运行时创建多个数据库模式?

c - Win32 API CopyFile() 无法发送多个文件

c - 在C中逐行逐字符读取文件

html - 将子组件作为新页面加载,而不是作为父组件主体的一部分