如何从静态上下文中获取 getclass().getResource() ?
我有一个函数,我试图将文件加载到 URL
对象,因为示例项目是这么说的。
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);
我尝试使用SecureFTP.class.getResource
,但仍然无法编译。
我对 Java 相当陌生,所以我知道我做错了什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
main 方法是静态方法,因此尝试访问 this(= 当前对象)将不起作用。
您可以将该行替换为
The main method is a static method, so trying to access
this
(= the current Object) will not work.You can replace that line by
来自:如何从静态方法调用 getClass()在Java中?
From: How to call getClass() from a static method in Java?
老问题,但这还没有说。您可以从静态上下文中执行此操作:
Old question but this hasn't been said yet. You can do this from a static context:
它无法编译,因为
getResource
采用资源名称(String
,而不是File
)作为参数,以便加载资源使用类加载机制(从类路径)。将其与File
一起使用是没有意义的。如果您想打开文件,只需使用FileInputStream
或FileReader
即可。请参阅 http: //docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29,并在下次出现此类错误时包含编译器错误消息问题。
It can't compile because
getResource
takes a resource name (aString
, and not aFile
) as parameter, in order to load a resource using the class loading mechanism (from the classpath). Using it with aFile
makes no sense. If you want to open a file, just use aFileInputStream
or aFileReader
.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.
应该做的伎俩!
Should do the trick!
这样做,以便它可以从静态方法或实例方法工作:
Do it this way so that it works EITHER from a static method or an instance method: