Get directory from classpath (getting a file now) - java

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());

Related

How to get the path of the file from source root in java?

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);

Trouble in creating file java

currently I'm working on a project and I have to change the savepath of my application. So I will firstly check if the directory exists using
File file = new File(path);
file.exists();
My problem is that the method file.exists() returns false even when I try to input C: as my path. Nevertheless, if I don't specify any folder, let say :
File file = new File("testFile.xml");
Then the new file will be created in the main directory. I suspect Eclipse automatically adds a relative path everytime I do the check since when I use text editor, the following returns true
new File("C:").exists()
Now, is there any way to tell Eclipse to recognise the path that I enter as an absolute path?
Thanks!
EDITED ****
I found that my problem is that Eclipse seems to auto append every file path that I create with the source directory
File = new File("C:/")
will give me
"C:\Users\Christopher\Documents\School Stuff\CS2103\JOBS\main\C:\"
which is automatically appended by eclipse with the project directory and hence, disabling me from creating file outside of my project directory
Could you try file.getAbsoluteFile().exists() ?
File.isAbsolute():
File file = new File(path);
if (file.isAbsolute()) {
}
in Eclipse, right click on project and go to run> run configuration and go to arguments give the default path for saving file.... project always create file on that location.
File fileTest = new File("C:/test");
if (!fileTest.exists()) {
if (fileTest.mkdirs()) {
fileTest.setReadable(true, false);
fileTest.setWritable(true, false);
} else {
System.out.println("Failed To Create Directories! :-"+ "C:/");
}
}

How to read file from relative path in Java project? java.io.File cannot find the path specified

I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

Getting the directory name in java

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

Getting file path in java

Is there a way for java program to determine its location in the file system?
You can use CodeSource#getLocation() for this. The CodeSource is available by ProtectionDomain#getCodeSource(). The ProtectionDomain in turn is available by Class#getProtectionDomain().
URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
File file = new File(location.getPath());
// ...
This returns the exact location of the Class in question.
Update: as per the comments, it's apparently already in the classpath. You can then just use ClassLoader#getResource() wherein you pass the root-package-relative path.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("filename.ext");
File file = new File(resource.getPath());
// ...
You can even get it as an InputStream using ClassLoader#getResourceAsStream().
InputStream input = classLoader.getResourceAsStream("filename.ext");
// ...
That's also the normal way of using packaged resources. If it's located inside a package, then use for example com/example/filename.ext instead.
For me this worked, when I knew what was the exact name of the file:
File f = new File("OutFile.txt");
System.out.println("f.getAbsolutePath() = " + f.getAbsolutePath());
Or there is this solution too: http://docs.oracle.com/javase/tutorial/essential/io/find.html
if you want to get the "working directory" for the currently running program, then just use:
new File("");

Categories

Resources