How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder
Related
The project name is 'producer'. I have a file located in project folder C:/Users/Documents/producer/krb5.conf.
If I want to write its relative path, should I write
File file = new File("krb5.conf");
or
File file = new File("producer/krb5.conf");
or
File file = new File("./krb5.conf");
?
You can use both your 1. and 3. option.
The 2. option would refer to C:/Users/Documents/producer/producer/krb5.conf.
For the purpose of testing you could try to get the absolute path from each file and print it.
// 1.
File file1 = new File("krb5.conf");
File file2 = new File("producer/krb5.conf");
File file3 = new File("./krb5.conf");
System.out.println(file1.getAbsolutePath());
// Output: C:\Users\Documents\producer\krb5.conf
System.out.println(file2.getAbsolutePath());
// Output: C:\Users\Documents\producer\producer\krb5.conf
System.out.println(file3.getAbsolutePath());
// Output: C:\Users\Documents\producer\.\krb5.conf
The 3. path may look a bit weird at first, but it also works.
C:\Users\Documents\producer\. points to the current directory, so it is essentially the same as C:\Users\Documents\producer.
I have a file in java under the src folder, I want to get its path at runtime relative to the source folder.
For example-
myProject
-- src
-- packageOne
-- SomeFile.java
I would like to have the result packageOne/SomeFile.java. I couldn't find a way, I tried getPath(), getAbsoultePath() and every similar method.
You want to construct a relative path. AFAIK there is no ready function to use.
Given that you have one of the ancestor nodes (src) and you have SomeFile.java, the following code might work but I did not try...
File src = new File("...");
File somefile = new File("...");
String relpath = somefile.getName();
File cursor = somefile.getParentFile();
while (!cursor.getAbsolutePath().equals(src.getAbsolutePath()) {
somefile = cursor.getName() + File.pathSeparator + somefile;
}
System.out.println("relative path: "+relpath);
I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.
URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());
How can I load this way a directory?
It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString().
You need to change below line
File folder = new File(url.toString());
with this line
File folder = new File(url.getPath());
You need path of that folder which will you get from URL.getPath() function.
I hope this is what you need.
If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.
Here is an example:
URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());
Assume final String fname = "/dir1/dir2/fname.ext". I do not wish to parse the string recursively in order to create the directories if they do not exist, and only then write to a file. I wish to use the given string, fname, for creating the directories and file if each of which does not exist.
This is the code you are looking for:
File myFile = new File("/dir1/dir2/fname.ext");
myFile.getParentFile().mkdirs();
// do your writing being sure the parent directories exist.
You can use mkdirs to create the path.
File f = new File("/dir1/dir2/fname.ext");
f.getParentFile().mkdirs();
And then work on the file itself.
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file