How to read file from relative path in Java projec

2019-01-02 14:49发布

问题:

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.

回答1:

If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths in java.io.File. 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();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

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



回答2:

The following line can be used if we want to specify the relative path of the file.

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


回答3:

The relative path works in in java using the . operator.

  • . means same folder as the currently running context.
  • .. means the parent folder of the currently running context.

So the question is how do you know the path where the java is currently looking?

do a small experiment

   File directory = new File("./");
   System.out.println(directory.getAbsolutePath());

Observe the output , you will come to know the current directory where java is looking . From there , simply use the ./ operator to locate your file.

for example if the output is

G:\JAVA8Ws\MyProject\content.

and your file is present in the folder MyProject simply use

File resourceFile = new File("../myFile.txt");

Hope this helps



回答4:

    InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
    try {
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String line=null;
            while((line=reader.readLine())!=null){
                System.out.println(line);
            }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


回答5:

try .\properties\files\ListStopWords.txt



回答6:

While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:

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


回答7:

I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :

Object obj  = parser.parse(new FileReader("./src/command.json"));


回答8:

If you are trying to call getClass() from Static method or static block the you can do the following way.

You can call getClass() on the Properties object you are loading into.

public static Properties pathProperties = null;

static { 
    pathProperties = new Properties();
    String pathPropertiesFile = "/file.xml;
    InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}


回答9:

If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

assume that the absolute path is:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt


标签: