-2

I am getting a string which contains the name of the file along woth extension for ex as shown below..

 String s = "abcdf.dat";// Now as shown file abcde having a .dat extension 

Now i want to store the file name only in another string but not the extension so I want to store in this format such as-

 String p= "abcdf"; //only file name please advise how to achieve this
T_V
  • 17,440
  • 6
  • 36
  • 48
Kumar Madan
  • 33
  • 1
  • 5

6 Answers6

1

You can use split(String regex) to get the name.

String fileName = "abcdf.dat";
String name = fileName.split("\\.")[0]; // abcdf
String ext = fileName.split("\\.")[1]; // dat

NOTE: "\\." is a regular expression.

1

Use String#split() method.

String abcdf = "abcdf.dat";
String result= abcdf.split("\\.")[0];

. is a meta character ,So you need to escape it before splitting.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can use-

String filename = s.substring(0, s.lastIndexOf("."));

Since File name can contain more than one dot (.) so till last dot would be the file name.

T_V
  • 17,440
  • 6
  • 36
  • 48
0
String s = "abcdf.dat";

String start = StringUtils.substringBefore(s, "."); // returns "abcdf"
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Abdul Rehman Janjua
  • 1,461
  • 14
  • 19
0
String p = s.substring(0, s.lastIndexOf("."));
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
0

Try this one

 String fileName = "abcdf.dat";

 String name = fileName.split(java.util.regex.Pattern.quote("."))[0];
 String ext = fileName.split(java.util.regex.Pattern.quote("."))[1];
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64