Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to create a file in a directory using relative Path

Tags:

java

I want to create a file in a new directory using the relative path. Creating the directory "tmp" is easy enough.

However, when I create the file, it is just located in the current directory not the new one. The code line is below.

    File tempfile = new File("tempfile.txt"); 

Have tried this also:

    File tempfile = new File("\\user.dir\\tmp\\tempfile.txt"); 

Clearly I'm misunderstanding how this method works. Your assistance is greatly appreciated.

EDIT: added currently used code line as well as the one I think might work for a relative path to clear up confusion.

like image 320
Sore Finger Tips Avatar asked Mar 11 '12 19:03

Sore Finger Tips


People also ask

How do I create a relative path to a file?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.

How do you refer to a relative path in Java?

Define Relative Path for Parent Directory in Java We can use the ../ prefix with the file path to locate a file in the parent directory. This is the relative path for accessing a file in the parent directory.

How do I save a file in a directory in Java?

Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();


2 Answers

File dir = new File("tmp/test"); dir.mkdirs(); File tmp = new File(dir, "tmp.txt"); tmp.createNewFile(); 

BTW: For testing use @Rule and TemporaryFolder class to create temp files or folders

like image 59
Stanislav Levental Avatar answered Sep 20 '22 17:09

Stanislav Levental


You can create paths relative to a directory with the constructors that take two arguments: http://docs.oracle.com/javase/6/docs/api/java/io/File.html

For example:

File tempfile = new File("user.dir/tmp", "tempfile.txt"); 

By the way, the backslash "\" can be used only on Windows. In almost all cases you can use the portable forward slash "/".

like image 42
Joni Avatar answered Sep 20 '22 17:09

Joni