从与.jar文件位于同一文件夹的文件中读取 [英] read from a file that is in the same folder as the .jar file
问题描述
有没有办法从与.jar文件位于同一文件夹的文件中读取?我正在尝试创建一个java程序,当我上交我的作业时必须从文件中读取。我转过来后,我不知道文件或程序将保存在哪里,所以我不认为我可以对保存文件的目录进行编码。这可能吗?问题是我必须将文件上传到CSX主机服务器,这是一个Linux服务器并从那里运行它。如果我在文件之前没有放置路径,它只会搜索当前的文件夹位置?
Is there a way to read from a file that is in the same folder as the .jar file? I am trying to create a java program that has to read from a file when I turn in my assignment. I do not know where the file or program will be held once I turn it over so I dont think I can encode the directory of the held file. Is this possible? The problem is that i have to upload the file to a CSX hosts server which is a linux server and run it from there. If I dont put a path before the file will it just search its current folder location?
推荐答案
如前所述注释,这仅适用于从jar所在的目录运行命令。
(在桌面应用程序的上下文中)
要访问 jar
的当前目录中的文件,您的路径
该文件前面应加一个点。示例:
(In the context of a desktop application)
To access a file that's in the current directory of the jar
, your path
to the file should be preceded by a dot. Example:
String path = "./properties.txt";
FileInputStream fis = new FileInputStream(path);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
// Read the file contents...
在本例中,有一个文本名为 properties.txt
的文件与 jar
在同一目录中。
此文件将由 jar
中包含的程序读取。
编辑:你说文件名不会更改,这个答案适用,因为您事先知道名称,当然,如果您更喜欢硬编码。
In this example, there is a text file called properties.txt
in the same directory as the jar
.
This file will be read by the program contained in the jar
.
you said the filename would not change, and this answer applies given that you know the name beforehand, of course, should you prefer to hardcode it.
这篇关于从与.jar文件位于同一文件夹的文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!