-3

I'm reading in file names as Strings. I don't know how long these file names will be but I know that all end in .txt. I want to remove the .txt leaving only the file name. Any ideas?

eric MC
  • 766
  • 2
  • 10
  • 36
  • 1
    Well, there's the obvious approach of checking that the string *does* end with `.txt`, and just taking a substring based on the original length - 4... have you tried that? – Jon Skeet May 03 '13 at 15:37
  • http://stackoverflow.com/questions/941272/how-do-i-trim-a-file-extension-from-a-string-in-java – J_Sizzle May 03 '13 at 15:37
  • 1
    *"Any ideas?"* Yes. Search the forum and show some effort before asking. – Andrew Thompson May 03 '13 at 15:55

4 Answers4

1
 int dot = file.getFileName().toString().lastIndexOf(".");
 String me = "File: " + file.getFileName().toString();
 System.out.println("File: " + file.getFileName().toString().substring(0,dot+1));
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
Kingsmentor
  • 55
  • 2
  • 13
0
yourString.subtring(0, yourString.length()-4);
DeadlyJesus
  • 1,503
  • 2
  • 12
  • 26
0
if(filepath.endsWith(".txt") {
    filepath = filepath.substring(0, filepath.lastIndexOf(".txt");
}
Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
0
If (filename.endsWith(".txt")) {
    filename = filename.substring(0, filename.length()-4);
}

Or:

filename = filename.replace(".txt", "");

(will also cut away any .txt inside but not at the end of the file)