Convert InputStream into FileInputStream

夙愿已清 提交于 2019-12-23 20:23:36

问题


I have read this post How to convert InputStream to FileInputStream on converting a InputStream into a FileInputStream. However, the answer does not work if you are using a resource that is in a jar file. Is there another way to do it.

I need to do this to get the FileChannel from a call to Object.class.getResourceAsStream(resourceName);


回答1:


You can't, without basically writing to a file. Unless there's a file, there can't be a FileInputStream or a FileChannel. If at all possible, make sure your code is agnostic to the input source - design it in terms of InputStream and ByteChannel (or whatever kind of channel is most appropriate).




回答2:


From the InputStream returned by Class.getResourceAsStream(), you can make a Channel with Channels.newChannel( InputStream ).

This is not the FileChannel you requested, but it is still a Channel. Is it sufficient to meet your needs?




回答3:


If you really need a file and you know that the resource is not inside a jar or loaded remotely, then you can use getResource instead.

URL resourceLocation = Object.class.getResource(resourcePath);
if (resourceLocation == null) { throw new FileNotFoundException(resourcePath); }
File myFile = new File(resourceLocation.toURI());

If you don't absolutely need a FileChannel or can't make assumptions about how your classpath is laid out, then Andy Thomas-Cramer's solution is probably the best.



来源:https://stackoverflow.com/questions/5355040/convert-inputstream-into-fileinputstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!