Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert InputStream to FileInputStream

Tags:

java

file-io

I have this line in my program :

InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");

But how can I get FileInputStream from it [Resource_InputStream] ?

like image 614
Frank Avatar asked Feb 28 '10 23:02

Frank


People also ask

How do I get FileReader from InputStream?

There is no way to convert the InputStream into a FileReader. What you would need to do is write the contents of the MultiPartFile into a real on-disk File, then open a FileReader to it. Well, you can certainly use an InputStreamReader to wrap a Reader around an InputStream.

What is the difference between InputStream and FileInputStream?

There is no real difference. FileInputStream extends InputStream , and so you can assign an InputStream object to be a FileInputStream object. In the end, it's the same object, so the same operations will happen. This behavior is called Polymorphism and is very important in Object-Oriented Programming.


2 Answers

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

like image 174
BalusC Avatar answered Oct 03 '22 08:10

BalusC


Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

like image 28
whiskeysierra Avatar answered Oct 03 '22 09:10

whiskeysierra