Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to get the name of a file from the absolute path and remove its file extension?

Tags:

java

string

file

I have a problem here, I have a String that contains a value of C:\Users\Ewen\AppData\Roaming\MyProgram\Test.txt, and I want to remove the C:\Users\Ewen\AppData\Roaming\MyProgram\ so that only Test is left. So the question is, how can i remove any part of the string.

Thanks for your time! :)

like image 325
Ewen Avatar asked Aug 09 '12 23:08

Ewen


2 Answers

If you're working strictly with file paths, try this

String path = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
File f = new File(path);
System.out.println(f.getName()); // Prints "Test.txt"

Thanks but I also want to remove the .txt

OK then, try this

String fName = f.getName();
System.out.println(fName.substring(0, fName.lastIndexOf('.')));

Please see this for more information.

like image 73
mre Avatar answered Oct 23 '22 07:10

mre


The String class has all the necessary power to deal with this. Methods you may be interested in:

String.split(), String.substring(), String.lastIndexOf()

Those 3, and more, are described here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html

Give it some thought, and you'll have it working in no time :).

like image 30
slezica Avatar answered Oct 23 '22 06:10

slezica