java relative path_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. 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? I am also doing this in my main so I'm having trouble using .getResource(). How would I do this? Thanks.

My files path is as followed from the properties in eclipse

/MyProject/src/data.txt

I've tried:

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

But that doesn't work?

回答1:

If you are using eclipse, place your text file in the root of the project folder, outside the /src and /bin folders. 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

回答2:

Use the src/ prefix before the file path/name.

String path = "src/data.txt";

回答3:

The path is relative to the directory you execute the "java" command.e.g.

/opt/projects/myproject>$ java -cp com.mycompany.mypackage.MyJavaClass

in this case the MyJavaClass would find files relative to the directory

/opt/projects/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

来源:https://stackoverflow.com/questions/15281428/java-relative-path-of-text-file-in-main

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值