如何从静态上下文中获取getclass()。getResource()? [英] How to get getclass().getResource() from a static context?

查看:160
本文介绍了如何从静态上下文中获取getclass()。getResource()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我试图将文件加载到 URL 对象,因为示例项目是这样说的。

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

我尝试使用 SecureFTP.class.getResource 但它仍然无法编译它。

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

我对Java很新,所以我知道我做错了什么。

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

推荐答案

它无法编译,因为 getResource 获取资源名称( a String ,而不是文件)作为参数,以便使用类加载机制加载资源(来自classpath)。使用文件是没有意义的。如果要打开文件,只需使用 FileInputStream FileReader

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.

参见 http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29 ,并包含编译器错误下次有这样的问题时留言。

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.

这篇关于如何从静态上下文中获取getclass()。getResource()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆