java 从资源路径到jar文件中的图像创建文件对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4597346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a file object from a resource path to an image in a jar file
提问by MBU
I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:
创建 jar 文件后,我需要从包含在 jar 文件中的图像的文件路径中创建一个 File 对象。如果尝试使用:
URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());
but it doesn't work. Does anyone know of another way to do it?
但它不起作用。有谁知道另一种方法来做到这一点?
采纳答案by mhaller
Usually, you can't directly get a java.io.File
object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:
通常,您无法直接获取java.io.File
对象,因为压缩存档中的条目没有物理文件。您要么使用流(在大多数情况下这是最好的,因为每个好的 API 都可以使用流),或者您可以创建一个临时文件:
URL imageResource = getClass().getResource("image.gif");
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));
回答by Blundell
To create a file on Android from a resource or raw file I do this:
要从资源或原始文件在 Android 上创建文件,我这样做:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
- Don't forget to close your streams etc
- 不要忘记关闭你的流等
回答by Will
This should work.
这应该有效。
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
回答by Konstantin Komissarchik
You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.
您不能为存档内的引用创建 File 对象。如果您绝对需要一个 File 对象,则需要先将该文件解压缩到一个临时位置。另一方面,大多数好的 API 也将采用输入流,您可以从存档中的文件中获取它。