How to convert InputStream to FileInputStream

后端 未结 3 1442
悲&欢浪女
悲&欢浪女 2020-12-07 23:49

I have this line in my program :

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

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 00:45

    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.

提交回复
热议问题