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

与世无争的帅哥 提交于 2019-12-08 23:22:34

问题


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 static void main(String[] args) throws IOException , ClassNotFoundException, SQLException , JSchException, SftpException{
        File file = new File("/home/xxxxx/.ssh/authorized_keys");
        URL keyFileURL = this.getClass().getClassLoader().getResource(file);

I tried using SecureFTP.class.getResource, but it still could not compile it.

I am fairly new to Java, so I know I am doing something wrong.


回答1:


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.




回答2:


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");



回答3:


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

Just use TheClassName.class instead of getClass().




回答4:


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

ClassLoader classLoader = ClassLoader.getSystemClassLoader();
classLoader.getResource("filename");



回答5:


SecureFTP.class.getClassLoader().getResource(<<your resource name>>); 

Should do the trick!



来源:https://stackoverflow.com/questions/8361947/how-to-get-getclass-getresource-from-a-static-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!