Reputation: 21
I want to split the following String
"C:\ATS\Script\SampleFiles\xml\books.xml"
to extract only name of the file (books.xml
)
I tried using the split function but couldn't split \
if (file.isDirectory()) {
String fol = file.getCanonicalPath() ;
String foln = fol.split("C:\\ATS\\Script\\SampleFiles\\xml")[1];
System.out.println("directory:" + foln);
}
I want the output to extract only the file name i.e books.xml
Upvotes: 0
Views: 70
Reputation: 13111
You can do it simpler
File dir = new File("D:\\foo");
File file = new File("D:\\foo\\test.txt");
System.out.println("file.getName() = " + file.getName()); // test.txt
System.out.println("dir.getName() = " + dir.getName()); // foo
Upvotes: 0
Reputation: 747
Use getFileName()
method in Path
Path path = Paths.get("C:/ATS/Script/SampleFiles/xml/books.xml");
System.out.println(path.getFileName().toString());
Output
books.xml
Upvotes: 2
Reputation: 358
Is this it?
String fol = ...
String split[];
split = fol.split("\\");
String foln = split[split.length-1];
Upvotes: 0