在java中从当前目录读取一个文件 [英] reading a file from current directory in java

查看:94
本文介绍了在java中从当前目录读取一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  String dataset =./myFile.dat; 

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



如何解决这个问题?当我给整个路径它的工作...
$ b $ pre $ String dataset =C:\\\\\\\\\\\\\\\\\\\\\\\\\\' \\p1\\src\\myFile.dat;


解决方案

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

  URL urlToData = this.getClass()。getResource(path /在/罐/到/ MYFILE.DAT); 

不要依靠用户。目录属性。取决于应用程序。它可能指向与应用程序或数据目录完全不同的地方。


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

String dataset = "./myFile.dat";

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

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

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

解决方案

If myFile.dat is 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..

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

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

这篇关于在java中从当前目录读取一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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