【发布时间】:2014-06-27 12:32:40
【问题描述】:
我创建了一个名为 FileCopyFromJAR 的类,它有一个名为 copy 的静态方法。这允许我使用 getResourceAsStream 将文件复制到 JAR 之外:
public static void copy(String source,String dest) throws IOException{
try{
File sourceFile = new File(source);
File destFile = new File(dest);
InputStream in = FileCopyFromJAR.class.getResourceAsStream(source);
OutputStream out = new FileOutputStream(destFile);
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf,0,len);
}
in.close();
out.close();
}
catch(IOException e){
throw e;
}
}
在我的代码中,我将通过执行以下操作来调用它(假设 test.txt 在我的 .jar 文件的根目录中):
FileCopyFromJAR.copy("/test.txt","c:\\test.txt");
但是,如果我在文件夹中指定文件夹或文件,则会收到 FileNotFoundException。这两个都返回错误:
FileCopyFromJAR.copy("folder\test.txt","c:\\test.txt");
FileCopyFromJAR.copy("folder", "c:\\folder");
我也尝试过使用各种组合,如 /folder\test.txt 等,但似乎没有任何效果。有没有办法让这项工作发挥作用,还是我必须使用其他方法?
【问题讨论】:
-
这是我刚刚悬赏的问题的重复,让我试着找到它。
-
@djechlin - 谢谢,那太好了!
-
你试过“文件夹/test.txt”吗?
-
@MadProgrammer 是的,我只是确定了。我试过 FileCopyFromJAR.copy("folder\\test.txt", "c:\\test.txt");我得到一个 NullPointerException。