Java- relative path of text file in main?

别说谁变了你拦得住时间么 提交于 2019-11-28 21:35:37

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

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

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!