[英]Eclipse can't read text file in src folder
I am implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files.我正在为我的一个类实现一个分支预测器,我试图从 Eclipse 中的 src 文件夹中读取文件,但由于某种原因它无法打开文件。 I have done this before with the exact same process so I'm not sure what is different.
我之前使用完全相同的过程完成了此操作,因此我不确定有什么不同。
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually. traceFile 是从命令行设置的,如果我打印“输入”,它将打印出正确的文件路径,我已经手动确认它在那里。
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening?有没有关于为什么会发生这种情况的见解? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked.
我尝试重新启动 Eclipse,刷新文件,并且还在另一个有效的程序上对其进行了测试。 No idea why it can't find this file.
不知道为什么找不到这个文件。
Resources on the classpath, ie available through the classloaders getResource
method, will not be files on the file system when your application is deployed as a jar file, or deployed in general.当您的应用程序部署为 jar 文件或一般部署时,类路径上的资源,即通过类加载器的
getResource
方法可用,将不是文件系统上的文件。 Do not use File
with such resources, instead use getResourceAsStream
to access the resource content.不要将
File
与此类资源一起使用,而是使用getResourceAsStream
来访问资源内容。
Besides, your code is wrong.此外,您的代码是错误的。
getResource()
returns a URL
. getResource()
返回一个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()
.如果您想要来自
URL
的File
对象,您应该使用new File(uri)
,其中URI
通过调用url.toURI()
。
File input = new File(loader.getResource(traceFile).toURI());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.