How to check if a directory is inside other directory - java

How can I check if a given file is under other file? For example, I have new Paths.get("/foo/bar/") and new Paths.get("./abc/def.jar").
And I want to check whether the second is under /foo/bar.
I can figure out some string based comparisons like path.toFile().getAbsolutePath().startsWith(path2.toFile().getAbsolutePath()), but that looks fragile and not right.

I've found this useful Path.startsWith( Path other ) method, so this worked for me:
inputPath.toAbsolutePath().startsWith(outputDirectory.toAbsolutePath())

Related

Get full path from FileSystem

I want to get the full path for a FileSystem which I created like this.
FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);
Whatever I tried until now only got me an output like / and thats it, but what i really need to get is:
C:/Users/username/AppData/Local/Temp/junit9210120109362016454/Parent/test.zip/
Is there any way to get this information from the FileSystem object? I know I could just take the parameter I used to create it in the first place, but I want to be sure I don't mix anything up and I think it's better like that for a unit-test
Based on the accepted answer I came up with this to solve my problem:
Paths.get(fs.toString(), "file.txt").toString()
Use
Path from java.nio.file.Path;
Path path = Paths.get(directory.toString());
String fullpath=path.toUri().toString()
which will give full path like file:///F:/somedir1/somdir2/17f5b00a-bd6e-4109-8ce5-85df79b51a00.jpg

Why Groovy and Java return a dot instead the file name?

In a piece of some Gradle code I want to get a current folder name without splitting the path. But all attempts that I tried:
Paths.get(".").getFileName()
new File(".").getName()
new File(".").name
, return a dot "." instead of the name. Is there some function that gives the name, not another string by which the folder could be addressed?
What is interesting, if I use:
String currentDirPath = new File(".").absolutePath
println currentDirPath
currentDirPath = currentDirPath.substring(0,currentDirPath.lastIndexOf("\\"))
println currentDirPath
String currentDir = currentDirPath.substring(currentDirPath.lastIndexOf("\\")+1)
, it is seen, that the path string looks as:
C:\Users\543829657\workspace\dev.appl.ib.cbl\application\.
So, it is simply incorrect to take the last substring after
'\'. But all those three functions take not the name of the name of the really actual folder, but the last "."!
Gradle is build upon Groovy, which is a JVM language, just like Java. So to get the current working directory, you can simply use the same ways you would use in Java. As an example, the following code will give you the name of the working directory, not the full path (check Frans answer).
new File('').absoluteFile.name
However, please mention that, in Gradle, you should not create or access files from the current working directory, but from the project (project.projectDir) or build (project.buildDir) directories, since you might accidentally build projects from lower directories, e.g. because Gradle checks for settings.gradle scripts in parent directories.
Is not
new File("").absolutePath
what you are looking for?
We should not really retrieve the absolute path that way.
In Gradle, you can use project.projectDir to get the project path or rootProject if its a multiproject or if you want to get a path of the file project.file('yourfile')

Save all files from a folder in a jar

First:
I know, this question was asked about 100 times already.
I know, someone already could have gave the right answer.
But anyway, I have to ask this again. I didn't found a solution working for me. sorry.
I'm writing a game in java. Of course I have many packages (folders) with sounds and pictures and so on. But these folders are each of variable size. So I want to save the content of such a folder dynamically in a list.
Usually, I was making this:
File f[] = new File(getClass.getResource("/home/res/").toURI()).listFiles();
Now I can iterate though this file object and save each file. Perfect. Really?
No. When I extract this Project into a jar archive, this fails. All because a uri isn't "hierarchical" or some stuff like this. See this exception:
C:\Users\Administrator\Desktop>java -jar Homework.jar
java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(Unknown Source)
at homework.moonface.src.Moonface.loadSounds(Moonface.java:94)
at homework.moonface.src.Moonface.<init>(Moonface.java:55)
at control.Overview.main(Overview.java:16)
Ok, I thought, so I need to get this path and add it manual into the file object. (new File("path"); But... this doesn't work. I'm getting the known error that the input wasn't written correctly, or when i try to cut of "file:" from the resource url, it breaks because in a jar its "jar:file:" and not "file:". But also if I cut of jar:file: I'm getting null.
So, please don't mark this as a duplicate, and try to explain this shortly for me. It would help thousand other, who don't understand other solutions who aren't solutions.
Try this :
URL jarResourceURL = getClass().getResource("/home/res/");
JarURLConnection jarURLConnection = (JarURLConnection) jarResourceURL.openConnection();
Enumeration<JarEntry> entries = jarURLConnection.getJarFile().entries();
while (entries.hasMoreElements()){
entries.nextElement(); // iterate over entries and do something
}
UPD: I was thinking about how spring framework's ClassPathXmlApplicationContext resolves the resources from jars. So i investigated the source code and foud that there is an utility class org.springframework.core.io.ClassPathResource which have a convenient interface (moreover there is a possibility to get the corresponding java.io.File instance using it) and can help you to solve the problem. Here is the doc :
http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/core/io/ClassPathResource.html

Java - from a class within a project, check if a file exists in a different project

I am within a project cd.ef.gh/country/terms/license/CreateLicense.java
From the class CreateLicense.java, I want to check if a file exists in a different project.
However the below code always return falls
File newfile = new File(uv.wx.yz/legal/expiry/notice/readme.txt)
if(newfile.exists()) // this always returns false , even though the readme.txt file is exactly at that location.
I am apparently missing a simple thing or overlooking something obvious here
Please help
Thanks

Files searching in Java

Because I asked wrong question last time, I want to correct my intention. How can I find file by name in specified folder? I have a variable with a name of this file and i want to find it in specified folder. Any ideas?
Maybe the simplest thing that works is:
String dirPath = "path/to/directory";
String fileName = "foo.txt";
boolean fileExistsInDir = new File( dirPath, fileName ).exists();
File is just a placeholder for a location in the file system. The location does not have to exist.
Use Finding files in Java as a starting point. It should have everything that you are looking for - ask another specific question if you get stuck.

Categories

Resources