25

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" ? –

dedmar
  • 401
  • 3
  • 12
  • 22

5 Answers5

41

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);
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
40

I usually use this solution described in other post:

import org.apache.commons.io.FilenameUtils;

String basename = FilenameUtils.getBaseName(fileName);
Oibaf it
  • 1,842
  • 16
  • 9
23

You could use the File class to get the file name:

File userFile = new File(strfullPath);
String filename = userFile.getName();

Using a File object has numerous benefits, including the ability to test the file exists:

if (userFile.isFile()) {
  // Yay, it's a valid file (not a directory and not an invalid path)
}

You also need to check the file has an extension before you try and strip it:

if (filename.indexOf(".") > 0) {
    filename = filename.substring(0, filename.lastIndexOf("."));
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
1

You can call the file.getName() method that returns the name of the file as String. Then you cut the extension.

String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf(".")+1);
Lukas Eichler
  • 5,689
  • 1
  • 24
  • 43
1
if (!filename.equals(""))    
{
        String [] fileparts = filename.split("\\.");
        String filename = fileparts[0]; //Get first part
}
Eric Lundmark
  • 229
  • 3
  • 13
Maheshbabu Jammula
  • 357
  • 1
  • 2
  • 11
  • In the future when answering questions please provide an explanation with any code samples explaining why this will work. – Chris Spittles Jul 02 '14 at 09:38
  • This fails to consider that a filename might have many dots. For example vendor.prod.min.js or some such. – Robert Jan 11 '19 at 14:31