Java How to get file name from absolute path and remove its extension?

I have a problem, I have a line containing the value C: \ Users \ Ewen \ AppData \ Roaming \ MyProgram \ Test.txt and I want to delete C: \ Users \ Ewen \ AppData \ Roaming \ MyProgram \ so that only Test So the question is how can I delete any part of the line.

Thank you for your time!:)

+6
source share
3 answers

If you work 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 .txt

Ok try this

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

See more details.

+6
source

The String class has all the necessary capabilities to solve this problem. Methods that may interest you:

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

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

Let him think and you will get to work immediately :).

+1
source

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

According to the documentation, the method "will process the file in Unix or Windows format." "The text after the last leading or trailing slash and to the last point 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 .

0
source

Source: https://habr.com/ru/post/922526/


All Articles