Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename without extension from full path [duplicate]

Tags:

I am making a program to store data from excel files in database. I would like the user to give in console the full path of the file and after the program to take only the file name to continue.

The code for loading the full path is:

String strfullPath = ""; Scanner scanner = new Scanner(System.in); System.out.println("Please enter the fullpath of the file"); strfullPath = scanner.nextLine(); String file = strfullPath.substring(strfullPath.lastIndexOf('/') + 1); System.out.println(file.substring(0, file.indexOf('.'))); 

After that I would like to have: String filename = .......

The full path that the user would type would be like this: C:\\Users\\myfiles\\Documents\\test9.xls

The filename that I would create would take only the name without the .xls! Could anyone help me how I would do this?

How i would do it if i would like to take as filename "test9.xls" ? –

like image 468
dedmar Avatar asked Apr 29 '13 07:04

dedmar


People also ask

How do you find the file name without an extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

How do I get filename in shell without extension?

Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

Does full path include filename?

Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.


2 Answers

I usually use this solution described in other post:

import org.apache.commons.io.FilenameUtils;  String basename = FilenameUtils.getBaseName(fileName); 
like image 173
Oibaf it Avatar answered Sep 21 '22 17:09

Oibaf it


You can do it like this:

String fname = file.getName(); int pos = fname.lastIndexOf("."); if (pos > 0) {     fname = fname.substring(0, pos); } 

or you can use the apache.commons.io.FilenameUtils:

String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt); 
like image 20
CloudyMarble Avatar answered Sep 17 '22 17:09

CloudyMarble