Eclipse 无法读取 src 文件夹中的文本文件
Eclipse can't read text file in src folder
我正在为我的 类 之一实现一个分支预测器,我试图从 Eclipse 中的 src 文件夹中读取文件,但由于某种原因它无法打开文件。我以前用完全相同的过程做过这个,所以我不确定有什么不同。
traceFile 是从命令行设置的,如果我打印 "input",它会打印出正确的文件路径,我已经手动确认它在那里。
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
是否知道为什么会发生这种情况?我已经尝试重新启动 Eclipse,刷新文件,并且还在另一个有效的程序上对其进行了测试。不知道为什么找不到 this 文件。
类路径上的资源,即可通过类加载器getResource
method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File
with such resources, instead use getResourceAsStream
访问资源内容。
此外,您的代码有误。 getResource()
returns一个URL
. If you want a File
object from a URL
, you should use new File(uri)
, where the URI
is obtained by calling url.toURI()
.
File input = new File(loader.getResource(traceFile).toURI());
我正在为我的 类 之一实现一个分支预测器,我试图从 Eclipse 中的 src 文件夹中读取文件,但由于某种原因它无法打开文件。我以前用完全相同的过程做过这个,所以我不确定有什么不同。
traceFile 是从命令行设置的,如果我打印 "input",它会打印出正确的文件路径,我已经手动确认它在那里。
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
是否知道为什么会发生这种情况?我已经尝试重新启动 Eclipse,刷新文件,并且还在另一个有效的程序上对其进行了测试。不知道为什么找不到 this 文件。
类路径上的资源,即可通过类加载器getResource
method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File
with such resources, instead use getResourceAsStream
访问资源内容。
此外,您的代码有误。 getResource()
returns一个URL
. If you want a File
object from a URL
, you should use new File(uri)
, where the URI
is obtained by calling url.toURI()
.
File input = new File(loader.getResource(traceFile).toURI());