This is the input as string:
"C:\jdk1.6.0\bin\program1.java"
I need output as:
Path-->C:\jdk1.6.0\bin\
file--->program1.java
extension--->.java
Watch out the "\" char. I easily got output for "/".
In Java Split () function, we split the string using various methods; the string class makes two methods to split the strings. Let’s see the available signatures as follows, This method splits the string by using the regular expression on the given string; the entire string splits the string, and the resultant return form as an array string.
Finally, the resultant return value returns the array of string which splits the string based on the matches of the regular expression. How does the split () Function work in Java? In Java Split () function, we split the string using various methods; the string class makes two methods to split the strings.
where <pathObject> is returned by a call to Paths.get (), and if you need multiple parts of the path returned in a string use: There are other useful methods at the Java Path and Paths doc pages. Methods getNameCount and getName can be used for a similar purpose.
This variant of the split method takes a regular expression as a parameter and breaks the given string around matches of this regular expression regex. Here, by default limit is 0. Returns: An array of strings is computed by splitting the given string. Throws: PatternSyntaxException – if the provided regular expression’s syntax is invalid.
The File class gives you everything you need:
File f = new File("C:\\jdk1.6.0\\bin\\program1.java");
System.out.println("Path-->" + f.getParent());
System.out.println("file--->" + f.getName());
int idx = f.getName().lastIndexOf('.');
System.out.println("extension--->" + ((idx > 0) ? f.getName().substring(idx) : "") );
EDIT: Thanks Dave for noting that String.lastIndexOf will return -1 if File.getName does not contain '.'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With