6

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! :)

mre
  • 43,520
  • 33
  • 120
  • 170
Ewen
  • 1,008
  • 2
  • 16
  • 24
  • Are you asking this in a more general direction of how to remove parts of a string, or specifically for strings containing file paths? – garbagecollector Aug 10 '12 at 00:02

3 Answers3

6

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.

Community
  • 1
  • 1
mre
  • 43,520
  • 33
  • 120
  • 170
1

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 :).

salezica
  • 74,081
  • 25
  • 105
  • 166
  • If you're working strictly with file paths, I think it's easier to just use the `File` class rather than `String.split` to parse the file name. – mre Aug 10 '12 at 00:09
  • Easier it is, but I don't think we should give such a shortcut (which involves extra objects, and dealing with a type semantically outside the immediate domain of the problem, which is strings) to someone that would ask this question in the first place :) What will he do when it's `:` and not `/` delimiting his paths? – salezica Aug 10 '12 at 00:12
  • Well, you're right in that my solution isn't flexible, nor elegant, but it is concise! :D – mre Aug 10 '12 at 00:22
  • Oh no I think your approach is **way** more elegant than mine (concise = elegant most of the time!). I would actually do it your way myself, it's just not very educational :( – salezica Aug 10 '12 at 00:25
0

I recommend using FilenameUtils.getBaseName(String filename). The FilenameUtils class is a part of Apache Commons IO.

According to the documentation, the method "will handle a file in either Unix or Windows format". "The text after the last forward or backslash and before the last dot is returned" as a String object.

String filename = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
String baseName = FilenameUtils.getBaseName(filename);
System.out.println(baseName);

The above code prints Test.