Quit text from string that references a path JAVA [duplicate] - java

This question already has answers here:
Get the filePath from Filename using Java
(5 answers)
Closed 2 years ago.
If i have a String that contains a path like
"D:\Folder\Folder2\file.txt"
, how can i remove the file and have only
"D:\Folder\Folder2"
Thank you for your time. :D

You could use the Apaches FilenameUtils..
This class defines six components within a filename (example
C:\dev\project\file.txt):
the prefix - C:\
the path - dev\project\
the full path -> C:\dev\project\
the name - file.txt
the base name - file
the extension - txt
So by using following code, you get the full path (without the filename):
getFullPath("D:\\Folder\\Folder2\\file.txt");
Please have a look at https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html

Java IO and NIO packages has classes for file handling - File and Path. All of these do same job to extract parent as Path, File or String and avoid hardcoding file separator:
import java.io.File:
File parent = new File("D:\\Folder\\Folder2\\file.txt").getParentFile();
String parent = new File("D:\\Folder\\Folder2\\file.txt").getParent();
import java.nio.file.Path:
Path parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent();
String parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent().toString();

String a = "D:\\Folder\\Folder2\\file.txt";
System.out.print(a.substring(0, a.lastIndexOf("\\")));

Related

Adding a single forward slash or double backward slash to directory path in java [duplicate]

This question already has answers here:
How to combine paths in Java?
(12 answers)
Path delimiter in windows and linux for java code
(2 answers)
Closed 2 years ago.
I am using JFileChooser to get a directory path in a project of mine. It is working perfectly, but there is a little problem. Suppose this is the directory structure:
->Home
->Documents
->Java
This is the code:
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int userSelection=fileChooser.showSaveDialog(this);
if(userSelection==JFileChooser.APPROVE_OPTION){
try{File fileTosave=fileChooser.getSelectedFile();
File newFile=new File(fileTosave.getAbsolutePath()+"satish.txt");
System.out.println(newFile);
this.dispose();}
catch(Exception e){}
}
If currently i am inside the java folder, it gives me the path Home/Documents/Java(or Home:\Documents\Java) in windows. What I want is that it should return the path which includes single forward slash or double forward slash (according to plaform) such that it looks like Home/Documents/Java/. I want to do this because later I have to append a file name to this path such that file path becomes Home/Documents/java/file.txt.
Any Idea on how to do this?
I don't want to add slashes manually because then I would also have to keep the platform in mind.
Thank you!
Use java.io.File.pathSeparator
/**
* The system-dependent path-separator character, represented as a string
* for convenience. This string contains a single character, namely
* <code>{#link #pathSeparatorChar}</code>.
*/
public static final String pathSeparator = "" + pathSeparatorChar;
Your code should look like
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int userSelection=fileChooser.showSaveDialog(this);
if(userSelection==JFileChooser.APPROVE_OPTION){
try{File fileTosave=fileChooser.getSelectedFile();
File newFile=new File(fileTosave.getParent() + File.separator +"satish.txt");
System.out.println(newFile);
this.dispose();}
catch(Exception e){}
}
Java doesn't provide a method or strategy to convert file paths as Strings to the format for different OS's out of the box. You would need to either write your own method to do this or take advantage of a library that has already solved this for you.
For example, you can use Apache Commons IO to solve this, using the method:
FilenameUtils.separatorsToSystem(String path)

How to get a full native path of the file in String format which is being uploaded [duplicate]

This question already has answers here:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
(14 answers)
Closed 4 years ago.
How to get a full native path of the file in String format which is being uploaded using and being used in a manged bean for its validation and upload? I also don't really want to use simple mode for p:fileUpload.
For example, if a file is being uploaded is from desktop then I want the path of the file as "C:\Users\\Desktop\" in a String format.
Any help would be really appreciated...
you can use java.nio.file.Path library
Path path = Paths.get("test.txt");
log("Path: " + path);
log("Absolute: " + path.isAbsolute());

How to get file from resources when blank space is in path [duplicate]

This question already has answers here:
Accessing files with spaces in filename from Java
(6 answers)
Closed 7 years ago.
I need parse .yml file with configuration.
File is located in src/main/resources/configFile.yml
Right now i have no problem until there is no blank space in some folder name in the path.
Example:
E:\Tomcat-7.0\webapps\applicationName\WEB-INF\classes\configFile.yml (OK)
E:\Tomcat 7.0\webapps\applicationName\WEB-INF\classes\configFile.yml (FAIL)
In second example i got java.io.FileNotFoundException.
I can not affect path. So i am looking for solution which will be able to handle it. Could you suggest how to proceed?
You should escape the space in the name, like:
"E:\Tomcat\ 7.0\webapps\applicationName\WEB-INF\classes\configFile.yml"
Or decode the path:
String decodedPath = URLDecoder.decode(path);

How to change file path location in java.io.File object [duplicate]

This question already has answers here:
What is meant by immutable?
(17 answers)
Closed 3 years ago.
The question says it all.
I have a File object which is pointing to /home/user/filename1.
If I call file.getAbsolutePath() then it would return /home/user/filename1
My question is that -
Can we change the path inside file object to a different location?
If yes, then how?
Thanks
"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "
From the File javadoc.
I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.
File oldfile =new File(file.getAbsolutePath());
String origPath = file.getCanonicalPath();
String destPath = origPath.replace(file.getName(),"");
String destFile = file.getName();
String n_destFile = destFile.replace("-a", "");
File newfile =new File(destPath+n_destFile);
A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?
As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.
Have a look at Apache Commons IO
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here you have a useful library to deal with files.

How to get the path of running java program [duplicate]

This question already has answers here:
Find where java class is loaded from
(12 answers)
Closed 9 years ago.
Is there a way to get the path of main class of the running java program.
structure is
D:/
|---Project
|------bin
|------src
I want to get the path as D:\Project\bin\.
I tried System.getProperty("java.class.path"); but the problem is, if I run like
java -classpath D:\Project\bin;D:\Project\src\ Main
Output
Getting : D:\Project\bin;D:\Project\src\
Want : D:\Project\bin
Is there any way to do this?
===== EDIT =====
Got the solution here
Solution 1 (By Jon Skeet)
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
This printed out:
file:/C:/Users/Jon/Test/foo/Test.class
Solution 2 (By Erickson)
URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());
Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
Try this code:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
replace 'MyClass' with your class containing the main method.
Alternatively you can also use
System.getProperty("java.class.path")
Above mentioned System property provides
Path used to find directories and JAR archives containing class files.
Elements of the class path are separated by a platform-specific
character specified in the path.separator property.
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}

Categories

Resources