How to open a file in another directory in java?

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

What you need to enter in the path in the parameter when creating the File object as follows:

File f = new File("/test2/doit.txt");
+5
source share
3 answers

Regardless of which operating system you can get, for example, a demo.txt file, for example

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

on windows where the file is located in D:\user\and

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

in *nixor *nuxwhere the file is in/usr/

In addition, the file, if it wants to access relatively, can be executed as (taking into account the Windows example):

Suppose I am in a song catalog in D: like:

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

Main.java, .

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

, F:/test, - :

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

- - , .

+2

Try below.

fr = new FileReader ("C:/Users/user/Desktop/java/test.txt"); 
-3
source

All Articles