简体   繁体   English

Java-主文本文件的相对路径?

[英]Java- relative path of text file in main?

I was wondering how to specifiy a relative path name to a text file that is stored in my src folder of a java project. 我想知道如何指定存储在java项目的src文件夹中的文本文件的相对路径名。 I would like to store a string with the path of this text file. 我想存储一个包含此文本文件路径的字符串。 For example if I had example.txt located in the src folder of my java project how would I go about finding its relative path? 例如,如果我的example.txt位于我的java项目的src文件夹中,我将如何找到它的相对路径? I am also doing this in my main so I'm having trouble using .getResource(). 我也在我的主要做这个,所以我在使用.getResource()时遇到了麻烦。 How would I do this? 我该怎么做? Thanks. 谢谢。

My files path is as followed from the properties in eclipse /MyProject/src/data.txt 我的文件路径如下所示,来自eclipse /MyProject/src/data.txt中的属性

I've tried: 我试过了:

String path = "/MyProject/src/data.txt"; String path =“/ MyProject / src / data.txt”;

But that doesn't work? 但这不起作用?

If you are using eclipse, place your text file in the root of the project folder, outside the /src and /bin folders. 如果您使用的是eclipse,请将文本文件放在/src/bin文件夹之外的项目文件夹的根目录中。 It should be now accessible via a relative path directly. 现在应该可以通过相对路径直接访问它。

If you want to access a file in src folder, you have to append the /src/ prefix before the file path/name 如果要访问src文件夹中的文件,则必须在文件路径/名称前附加/src/前缀

在文件路径/名称前使用src/前缀。

String path = "src/data.txt"; 

The path is relative to the directory you execute the "java" command.eg 该路径相对于执行“java”command.eg的目录

 /opt/projects/myproject>$ java -cp <whatever your classpath is that contains your class files> com.mycompany.mypackage.MyJavaClass

in this case the MyJavaClass would find files relative to the directory 在这种情况下,MyJavaClass将找到相对于目录的文件
/opt/projects/myproject /选择/项目/ MyProject的

There is another way to do this if you like: you can use load resources, which are found via the classpath mechanism. 如果您愿意,还有另一种方法可以执行此操作:您可以使用通过类路径机制找到的加载资源。

 getClass().getResource("foo.txt");

You can see this posting for more info 您可以查看此帖子以获取更多信息

Preferred way of loading resources in Java 在Java中加载资源的首选方式

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

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