How to convert InputStream to FileInputStream

JavaFile Io

Java Problem Overview


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] ?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

You need something like:

	URL resource = this.getClass().getResource("/path/to/resource.res");
	File is = null;
	try {
		is = new File(resource.toURI());
	} catch (URISyntaxException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		FileInputStream input = new FileInputStream(is);
	} catch (FileNotFoundException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavawhiskeysierraView Answer on Stackoverflow
Solution 3 - JavaNenad BulatovićView Answer on Stackoverflow