How to get getclass().getResource() from a static context?

前端 未结 5 2017
名媛妹妹
名媛妹妹 2020-12-30 19:14

I have a function where I am trying to load a file to a URL object, because the example project said so.

public class SecureFTP {

    public s         


        
相关标签:
5条回答
  • 2020-12-30 19:28

    Old question but this hasn't been said yet. You can do this from a static context:

    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    classLoader.getResource("filename");
    
    0 讨论(0)
  • 2020-12-30 19:35
    SecureFTP.class.getClassLoader().getResource(<<your resource name>>); 
    

    Should do the trick!

    0 讨论(0)
  • 2020-12-30 19:37

    It can't compile because getResource takes a resource name (a String, and not a File) as parameter, in order to load a resource using the class loading mechanism (from the classpath). Using it with a File makes no sense. If you want to open a file, just use a FileInputStream or a FileReader.

    See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29, and include the compiler error message next time you have such a question.

    0 讨论(0)
  • 2020-12-30 19:47

    The main method is a static method, so trying to access this (= the current Object) will not work. You can replace that line by

    URL keyFileURL = SecureFTP.class.getClassLoader().getResource("/home/xxxxx/.ssh/authorized_keys");
    
    0 讨论(0)
  • 2020-12-30 19:48

    From: How to call getClass() from a static method in Java?

    Just use TheClassName.class instead of getClass().

    0 讨论(0)
提交回复
热议问题