我想将文件复制到另一个目录。我知道这个问题已被问过数百万次,我阅读了大量有关此问题的答案,但我似乎无法使其工作。这是我当前正在使用的代码:
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):
最佳答案
复制文件的标准方法不起作用,因为您正在尝试将文件从 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/