Java,从当前目录中读取文件? [英] Java, reading a file from current directory?

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

问题描述

我想要一个从当前目录(运行.class文件的同一目录)读取用户指定文件名的java程序。

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).

换句话说,如果用户将文件名指定为myFile.txt,并且该文件已在当前目录中:

In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:

reader = new BufferedReader(new FileReader("myFile.txt"));

不起作用。为什么?

我在Windows中运行它。

I'm running it in windows.

推荐答案

当前目录不是(必然).class文件所在的目录。它是进程的工作目录。 (即:启动JVM时所在的目录)

The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)

您可以从同一目录 * 加载文件作为.class文件使用 getResourceAsStream() 。这将为您提供一个InputStream,您可以使用 InputStreamReader

You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.

* 请注意这个目录实际上可能是一个jar文件,具体取决于加载类的位置。

*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.

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

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