简体   繁体   English

如何独立于Java项目的路径打开文件?

[英]How to open a file independently of the path of the Java project?

I'm working with Eclipse and there, I have Java Project with the name "Test" which also contains text files. 我正在使用Eclipse,在那里,我有Java Project,名称为“ Test”,其中还包含文本文件。 A class in this Project should be able to read in one of these files with a BufferedReader. 该项目中的类应能够使用BufferedReader读取这些文件之一。 This is my current code for that: 这是我目前的代码:

BufferedReader in = new BufferedReader(new FileReader("C:/Users/workspace/Test/testFile.txt"));

My file is always in the Project, but when I move the Project to another path, the file path changes, too, so I have to adjust the code with the new path. 我的文件始终在Project中,但是当我将Project移到另一个路径时,文件路径也会更改,因此我必须使用新路径调整代码。 I dont't want that, because it's impractical, so what can I do? 我不希望这样做,因为这是不切实际的,该怎么办? How can I get the path of the Project? 我如何获得项目的路径?

You can add file to resources folder and read like 您可以将文件添加到资源文件夹并读取如下

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

Try something like this: 尝试这样的事情:

File currentDirFile = new File(".");
String fileDir = currentDirFile.getAbsolutePath();

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

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