How to read the file from the relative path in the Java project? can not find the specified path

I have a project with 2 packages:

  1. tkorg.idrs.core.searchengines
  2. tkorg.idrs.core.searchengines

In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:

File file = new File("properties\\files\\ListStopWords.txt");

But have this error:

The system cannot find the path specified

Can you give a solution to fix it? Thanks.

If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths in They are dependent on the current working directory over which you have totally no control from inside the Java code.

Assuming that ListStopWords.txt is in the same package as FileLoader class:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

Or if all you're after is an InputStream of it:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed it immediately to the load() method.

Properties properties = new Properties();

Note: when you're trying to access it from inside static context, then use FileLoader.class instead of getClass() in above examples.