Tiny Jaguar
Tiny Jaguar

Reputation: 433

How to open file in another directory in java?

How to open a file that is not present in the current directory but in another directory. For example, I have a folder F:/test and my file is in F:/test/test2/doit.txt and D:/test3/doit2.txt

What to enter in path in parameter while making File object as follows :

File f = new File("/test2/doit.txt");

Upvotes: 6

Views: 35669

Answers (4)

abdella
abdella

Reputation: 734

File inside of a project can be open as:

       File file = new File(path);

or

       File file = new File(./path);

where path is relative path from the project.

For example, when the project name is test and the file with name fileName is inside the test project:

      File file = new File("fileName");

or

      File file = new File("./fileName");

Upvotes: 0

ssaitala
ssaitala

Reputation: 135

Please try the code below on Windows OS:

reader = new FileReader ("C:/Users/user/Desktop/java/test.txt"); 

Upvotes: -1

Paweł Piecyk
Paweł Piecyk

Reputation: 2789

Assuming that you are running your program from F:/test you should use something like:

File f = new File("./test2/doit.txt");

Using hardcoded absolute paths isn't a good idea - your program might not work when user has different directory structure.

Upvotes: 6

TechSpellBound
TechSpellBound

Reputation: 2555

Irrespective of which operating system, a file for example, demo.txt can be accessed like

File file = new File("/d:/user/demo.txt");

in Windows where the file is at D:\user\ and

File file = new File("/usr/demo.txt");

in *nix or *nuxwhere the file is at /usr/

Also, a file if wanted to be accessed relatively can be done as (considering the Windows example) :

Suppose I am in the songs directory in D: like:

D:/
|
|---songs/
|   |
|   |---Main.java
|
|---user/
    |
    |---demo.txt

and the code is inside Main.java, then the following code works.

File file = new File("../user/demo.txt");

Upvotes: 8

Related Questions