java java从当前目录读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6853877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:36:05  来源:igfitidea点击:

reading a file from current directory in java

javafile

提问by cMinor

I have a java project where I am reading a file. As the file is in the current directory I am doing this:

我有一个 java 项目,我正在读取一个文件。由于文件在当前目录中,我这样做:

String dataset = "./myFile.dat";

But I am getting: java.io.FileNotFoundExceptionsaying It can not find the file.

但我得到:java.io.FileNotFoundException说它找不到文件。

How to fix this? When I give entire path it works...

如何解决这个问题?当我给出整个路径时,它会起作用......

String dataset = "C:\eclipse\workspace\p1\src\myFile.dat";

采纳答案by Andrew Thompson

If myFile.datis an application resource, it should be included in a Jar that is on the run-time class-path of the application. Then an URL to the resource can be formed using..

如果myFile.dat是应用程序资源,则应将其包含在应用程序运行时类路径上的 Jar 中。然后可以使用..形成资源的 URL。

URL urlToData = this.getClass().getResource("path/in/jar/to/myFile.dat");

Don'trely on the user.dirproperty. Depending on how the app. is started, it might point somewhere very different to the directory of the application or data.

不要依赖user.dir财产。取决于应用程序的方式。启动时,它可能指向与应用程序或数据目录非常不同的某个地方。

回答by Eng.Fouad

Try this:

试试这个:

String dataset = System.getProperty("user.dir") + "/myFile.dat";