简体   繁体   English

java中的.txt文件的路径

[英]path of a .txt file in java

I work with NetBeans IDE an I have a .txt file saved in src/myapp folder. 我使用NetBeans IDE,我有一个保存在src / myapp文件夹中的.txt文件。 If I run from the IDE, this recognise my 如果我从IDE运行,这会识别我的

File file=new File("src/myapp/mytext.txt");

But if I build the jar file and double click it or launch it from command line I get this error: 但是,如果我构建jar文件并双击它或从命令行启动它,我会收到此错误:

java.io.FileNotFoundException: src\myapp\mytext.txt

I could insert absolute path, but how can I run my jar independently by the position of my project in the computer? 我可以插入绝对路径,但是如何根据项目在计算机中的位置独立运行我的jar?

You can obtain the file path indepently of its position with the following: 您可以使用以下内容独立获取其位置的文件路径:

ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("mytext.txt").toString();

Java is expecting to find the file relative to your working directory. Java期望找到相对于您的工作目录的文件。 So by hardcoding the file in src/myapp/mytext.txt you are expecting the user of your application to have the file under the same folder structure. 因此,通过在src/myapp/mytext.txt对文件进行硬编码,您希望应用程序的用户将文件置于相同的文件夹结构下。

If you are expecting the file to be at the same level of your jar file, you can just use ./mytext.txt . 如果您希望文件与jar文件处于同一级别,则可以使用./mytext.txt Do not put your mytext.txt under the src in your project. 不要将mytext.txt放在项目中的src下。 That is for sources you want to compile and/or bundle inside your jar file. 这适用于要在jar文件中编译和/或捆绑的源。 In NetBeans move it outside the /src folder, that way when you run the program from your IDE or when you run it externally from your Jar file you find the file at the same level. 在NetBeans中,将它移到/src文件夹之外,当您从IDE运行程序时,或者从Jar文件外部运行它时,您会在同一级别找到该文件。

If you want the user to be able to specify the location himself of the file, you can also read the command line arguments (the arguments to your public static void main(String[] args) ). 如果希望用户能够指定文件本身的位置,还可以读取命令行参数( public static void main(String[] args) )。

没有这样的问题

File file=new File("./src/myapp/mytext.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM