151

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 I have this error:

The system cannot find the path specified

Can you give a solution to fix it?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tiendv
  • 2,307
  • 7
  • 23
  • 34

16 Answers16

207

If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. 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 your FileLoader class, then do:

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

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

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

This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.

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 the InputStream 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 (or whatever YourClass.class) instead of getClass() in above examples.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Was FileLoader removed from java? I am trying to do this from a static context (java 6) and I can't find any way to import it and it keeps telling me it cannot resolve to a type. Strangely enough, it autocompleted as I typed it, but then proceeded to give me an error. – turbo Oct 07 '13 at 18:57
  • 2
    oh, it's supposed to be ClassLoader.class. – turbo Oct 07 '13 at 19:12
  • 4
    @turbo: `FileLoader` is OP's own custom class. It's supposed to be exactly that class wherein you're attempting to obtain the resource. Thus, so `NameOfYourCurrentClass.class.getResourceAsStream(...)`. The `ClassLoader.class` will fail if the `ClassLoader` class is being loaded by a different classloader, which may happen in an "enterprise" application with a hierarchy of multiple classloaders (like a Java EE web application). – BalusC Oct 07 '13 at 19:30
  • Ohh, I see. I didn't understand that it was dependent. Thanks for clearing that up! – turbo Oct 07 '13 at 19:32
  • It might be better to do following: Scanner scan = new Scanner(url.getPath()); content = scan.useDelimiter("\\Z").next(); scan.close(); – Daniil Shevelev Jan 10 '14 at 13:59
  • 16
    Any suggestion for if the file is not in the same package? In my instance I'm trying to open a file which is located in a test package. – Robin Newhouse Oct 09 '14 at 01:19
85

The relative path works in Java using the . specifier.

  • . 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 ./ specifier 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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Samrat
  • 1,329
  • 12
  • 15
  • 1
    after hours of searching this answer provided me with the solution –  Jun 15 '20 at 20:30
47

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");  
Mohamed Taher Alrefaie
  • 15,698
  • 9
  • 48
  • 66
santhosh
  • 479
  • 4
  • 2
10
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) {
    e.printStackTrace();
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
6

try .\properties\files\ListStopWords.txt

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
bUg.
  • 912
  • 9
  • 11
5

I could have commented but I have less rep for that. Samrat's answer did the job for me. It's better to see the current directory path through the following code.

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

I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.

    ./test/conf/appProperties/keystore 
abdev
  • 597
  • 4
  • 17
  • I'm running my code through tomcat and so the current directory is not the project folder - How do i define the relative path to the project root? Im currently using the hard path:"C:\\Users\\user\\Desktop\\Repositories\\L1_WebShop\\dblogs.log"; – Tiago Redaelli Oct 05 '19 at 20:23
  • @TiagoRedaelli check out this ques : https://stackoverflow.com/questions/12843217/how-to-get-relative-path-of-current-directory-in-tomcat-from-linux-environment-u – abdev Oct 09 '19 at 05:18
5

enter image description here

Assuming you want to read from resources directory in FileSystem class.

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);

System.out.println(Files.readString(path));

Note: Leading . is not needed.

R Sun
  • 1,353
  • 14
  • 17
4

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());
iamallama
  • 606
  • 6
  • 10
1

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"));
sver
  • 866
  • 1
  • 19
  • 44
1

For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem

J.Luan
  • 227
  • 2
  • 5
1

For me it worked with -

    String token = "";
    File fileName = new File("filename.txt").getAbsoluteFile();
    Scanner inFile = null;
    try {
        inFile = new Scanner(fileName);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    while( inFile.hasNext() )
    {
        String temp = inFile.next( );  
        token = token + temp;
    }
    inFile.close(); 
    
    System.out.println("file contents" +token);
Check
  • 23
  • 2
0

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";
//      Now go for getClass() method
        InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
    }
M.Abdullah Iqbal
  • 219
  • 1
  • 17
arun_kk
  • 382
  • 2
  • 5
  • 14
0

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
pilsetnieks
  • 10,330
  • 12
  • 48
  • 60
KR N
  • 11
0

String basePath = new File("myFile.txt").getAbsolutePath(); this basepath you can use as the correct path of your file

0

if you want to load property file from resources folder which is available inside src folder, use this

String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();  
p.load(resourceStream);  
      
    System.out.println(p.getProperty("db")); 

db.properties files contains key and value db=sybase

Ali Can
  • 564
  • 3
  • 15
0

May be your sturcture is like this [enter image description here][1] main

  • java
    • filesystem
      • FileLoader.java
    • resource
      • 1.txt

And you can get the file 1.txt through some methods, here are some cases

public class Demo {
    public static void main(String[] args) {
        //1 you can use Path class
        Path path = Paths.get("src/main/java/resource/1.txt");
        System.out.println(path.toAbsolutePath());
        // and you can convert path to a file , then you ge file object.
        File file = path.toFile();
        System.out.println(" ------------- 2  ----------------");
        //2 get file object through File Class ,  and you need to use b scheme
        File a = new File("/");
        File b = new File("src/main/java/resource/1.txt");
        File c = new File("./");
        File d = new File(".");
        System.out.println(a.getAbsolutePath());
        System.out.println(b.getAbsolutePath());
        System.out.println(c.getAbsolutePath());
        System.out.println(d.getAbsolutePath());

        System.out.println(" \n\n------------- 3  ----------------");


        //3.  the right answer is put your resource file into resources folder(path is <Your_Project>/src/main/resources)
        // and when your project compiled , the files of resources will be added into target/classes folder
        // and you can get file through your Class

        URL e = Demo.class.getResource("/2.txt");
        URL f = Demo.class.getResource(" 2.txt");
        System.out.println(e.getPath());
//        System.out.println(f.getPath());  your will get a nullPointException here ,detailed information you can get in getResource Method

    }
}


  [1]: https://i.stack.imgur.com/gO3Ue.png