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);
Related
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");
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()).
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 /[^/]+/[^/]+$
Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...
Is there any easy way to convert a URL that contains to two-byte characters into an absolute path?
The reason I ask is I am trying to find resources like this:
URL url=getClass().getResources("/getresources/test.txt");
String path=url.toString();
File f=new File(path);
The program can't find the file. I know the path contain '%20' for all spaces which I could convert but my real problem is I'm using a japanese OS and when the program jar file is in a directory with japanese text (for example デスクトップ) I get the URL-encoding of the directory name,
like this:
%e3%83%87%e3%82%b9%e3%82%af%e3%83%88%e3%83%83%e3%83%97
I think I could get the UTF-8 byte codes and convert this into the proper characters to find the file, but I'm wondering if there is an easier way to do this. Any help would be greatly appreciated.
nt
URL url = getClass().getResource("/getresources/test.txt");
File f = new File(url.toURI());
If you were interested in getting Path from URL, you can do:
Path p = Paths.get(url.toURI());
File has a constructor taking an argument of type java.net.URI for this case:
File f = new File(url.toURI());
Another option for those who use Java 11 or later:
Path path = Path.of(url.toURI());
or as a string:
String path = Path.of(url.toURI()).toString();
Both methods above throw a URISyntaxException that can be safely ignored if the URL is guaranteed to be a file URL.