我已经将我的应用程序部署到jar文件中。当我需要将资源文件中的数据复制到jar文件之外时,我使用以下代码:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File src = new File(resourceUrl.toURI()); //ERROR HERE
File dst = new File(CurrentPath()+"data.sav"); //CurrentPath: path of jar file don't include jar file name
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
// some excute code here
我遇到的错误是:
URI不是分层的
。但在IDE中运行时,我并没有遇到此错误。如果根据StackOverFlow上其他帖子的建议更改上述代码:
InputStream in = Model.class.getClassLoader().getResourceAsStream("/resource/data.sav");
File dst = new File(CurrentPath() + "data.sav");
FileOutputStream out = new FileOutputStream(dst);
//....
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) { //NULL POINTER EXCEPTION
//....
}
data.sav
而不需要起始/
。但是在问题中,data.sav
在根包中,因此在这种情况下,他需要在前面加上/
。 - dash1eFile
对象,所以我创建了一个临时的File
并将内容从InputStream
复制到File
对象中。使用FileUtils.copyInputStreamToFile(inputStream, file);
- Vishal Patel