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.
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.
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.
Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();
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
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 "/".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With