Different ways of loading a file as an InputStream

前端 未结 6 606
予麋鹿
予麋鹿 2020-11-22 04:02

What\'s the difference between:

InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName)

and

InputSt         


        
6条回答
  •  既然无缘
    2020-11-22 04:31

    Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...

    I put file.txt in c:\temp\ and I put c:\temp\ on the classpath.

    There is only one case where there is a difference between the two call.

    class J {
    
     public static void main(String[] a) {
        // as "absolute"
    
        // ok   
        System.err.println(J.class.getResourceAsStream("/file.txt") != null); 
    
        // pop            
        System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null); 
    
        // as relative
    
        // ok
        System.err.println(J.class.getResourceAsStream("./file.txt") != null); 
    
        // ok
        System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null); 
    
        // no path
    
        // ok
        System.err.println(J.class.getResourceAsStream("file.txt") != null); 
    
       // ok
       System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null); 
      }
    }
    

提交回复
热议问题