Tony Tannous
Tony Tannous

Reputation: 14871

System can't find path

Trying to practice Java by doing basic functionality like reading input.

I am trying to parse movies-sample.txt found in:

C:\University\BigDataManagement\Data-Mining\hw1\src\main\resources\movies-sample.txt

Trying to reach movies-sample.txt from

C:\University\BigDataManagement\Data-Mining\hw1\src\main\java
   \univ\bigdata\course\MoviesReviewsQueryRunner.java

Using the answer found here on how to parse a large file line by line.

File file = new File("../../../../../resources/movies-sample.txt");

I am getting the following error:

The system cannot find the path specified

Given the above two paths, what am I doing incorrect?

Upvotes: 2

Views: 320

Answers (2)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36441

If you run your program directly from command line, then the path must be related to your current directory.

If you run your program from an IDE, then the current directory of the runnin program depends on the IDE and the way it is configured.

You can determine what is the current directory with System.getProperty("user.dir")

Whatever, hard coding a path in an application is always a bad thing because you cannot ensure where the run was launched from. Either:

  • it is a user resource, then its path must be input in some way (open... in GUIs apps)
  • it is a resource needed by the app to run correctly and it should be embedded in some way into the app itself (look for Resource Bundle)
  • it is a kind of optional external resource (config file for example, or path specified in a config file) and its location should be computed in some way.

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32165

If it's a web app then the resources folder is your root element, otherwise it will be the src folder as mentioned in comments.

In your case here as you are writing a standalone Java program and as your file is loacted in the resources folder, you can use CLassLoader to read the file as a stream.

This is how should be your code:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("movies-sample.txt");

Then you will be able to read the is stream line by line.

Upvotes: 2

Related Questions