Jump one folder up in a URL in Java - java

I have a URL that I get as below:
String jarFilePath = getClass().getProtectionDomain().getCodeSource().getLocation()
This would get me the complete path to the jar file. Now how do I jump one folder up and append some other path to it? For example., if the jarFilePath is something like:
c:/path/to/jar/file.jar
I want to jump one folder up and append another relative path like below:
c:/path/to/resources/path/to/resources/
Where the folders resources and jar are at the same directory level in the file system.

File f = new File("C:/path/to/jar/file.jar");
File dest = new File(f.getParentFile().getParentFile(), "resources/path/to/resources");

Just use the File-Object, that makes a lot of things easier:
import java.io.File;
String pathname = "c:/path/to/jar/file.jar";
File f = new File(pathname);
String p = f.getParent();

Try and use a File object:
File jarFile = new File(jarFilePath);
File newFolder = new File( jarFile.getParentFile().getParentFile(), "resources/path/to/resources");
If you want to use the path as a string, try using Apache Commons IO's FilenameUtils:
String resourcesPath = FilenameUtils.normalize( FilenameUtils.getPath(jarFilePath) + "/../resources/path/to/resources");

You have several ways.
You can split the path into it's elements and rebuild it until array.length -3 (-1 would be filename, -2 the last folder)
You could simple remove the file and append another ../ (which just means: "Go one directory back") (that would be something like this then: c:/path/to/jar/../resources/path/to/resources/)
You gould use a regex to get rid of the last folder and file. something like /[^/]+/[^/]+$

Related

How to get path to package in Eclipse (Java)

I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");

Java parse File-path with different working directory

I have a file which contain several paths, like . (relative) or /Users/...../ (absolut). I need to parse the paths that are relative to the directory of the file that contains the paths and not the working-directory and create correct File-instances. I can not change the working directory of the Java-Program, since this would alter the behaviour of other components and i also have to parse several files. I don't think public File(String parent, String child)does what i want, but i may be wrong. The documentation is quite confusing.
Example:
file xy located under /system/exampleProgram/config.config has the following content:
.
/Users/Name/file
./extensions
i want to resolve these to:
/system/exampleProgram/
/Users/Name/file
/system/exampleProgram/file/
So, I am going to assume that you have access to the path of the file you opened (either via File.getAbsolutePath() if it was a File descriptor or via a regex or something)...
Then to translate your relative paths into absolute paths, you can create new File descriptions with your opened file, like so:
File f = new File(myOpenedFilePath);
File g = new File(f, "./extensions");
String absolutePath = g.getCanonicalPath();
When you create a file with a File object and a String, Java treats the String as a path relative to the File given as a first argument. getCanonicalPath will get rid of all the redundant . and .. and such.
Edit: as Leander explained in the comments, the best way to determine whether the path is relative or not (and thus whether it should be transformed or not) is to use file.isAbsolute().
Sounds like you probably want something like
File fileContainingPaths = new File(pathToFileContainingPaths);
String directoryOfFileContainingPaths =
fileContainingPaths.getCanonicalFile().getParent();
BufferedReader r = new BufferedReader(new FileReader(fileContainingPaths));
String path;
while ((path = r.readLine()) != null) {
if (path.startsWith(File.separator)) {
System.out.println(path);
} else {
System.out.println(directoryOfFileContainingPaths + File.separator + path);
}
}
r.close();
Don't forget the getCanonicalFile(). (You might also consider using getAbsoluteFile()).

Create directory at given path in Java - Path with space

I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
You should us \\ for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes / so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
You need to escape your path (use \\ in your path instead of \) and you also need to use String, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator) or accesing the equivalent field in the File class. Also check this question.
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();

Get path directory only and discard file in Java

How do we actually discard last file from java string and just get the file path directory?
Random Path input by user:
C:/my folder/tree/apple.exe
Desired output:
C:/my folder/tree/
closest solution i found is from here . The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.
The easiest and most failsafe (read: cross-platform) solution is to create a File object from the path.
Like this:
File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
Try that:
String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);

How to get the excel file path using java code

String dirPath = fileObj.getParentFile().getAbsolutePath();
system.out.println(dirPath);
I tried this way but its returning the Java Project Path that is Workspace path..
.getParentFile() is probably returning the parent directory, which depending on the location of your file could be the project directory. If fileObj is an object of type File, just try using fileObj.getAbsolutePath() instead.
So try this:
File fileObj = new File("myFile.xls");
String dirPath = fileObj.getAbsolutePath();
System.out.println(dirPath);
This should result in output similar to:
C:/[your project directory]/myFile.xls
JavaDoc for getParentFile():
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#getParentFile()

Categories