Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split the path..?

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 "/".

like image 658
yuvaraj Avatar asked Dec 13 '10 18:12

yuvaraj


People also ask

How to split a string in Java?

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.

What is the return value of split () function in Java?

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.

How do I get multiple parts of the path in Java?

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.

What is the use of split method in JavaScript?

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.


1 Answers

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 '.'.

like image 57
Kurt Kaylor Avatar answered Nov 15 '22 17:11

Kurt Kaylor