41

I'm basically trying to split a string on the last period to capture the file extension. But sometimes the file doesn't have any extension, so I'm anticipating that.

But the problem is that some file names have periods before the end like so...

/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3

So when that string comes up it chops it at "02 Drake - Connect (Feat."

This is what I've been using...

String filePath = intent.getStringExtra(ARG_FILE_PATH);
String fileType = filePath.substring(filePath.length() - 4);
String FileExt = null;
try {
    StringTokenizer tokens = new StringTokenizer(filePath, ".");
    String first = tokens.nextToken();
    FileExt = tokens.nextToken();
}
catch(NoSuchElementException e) {
    customToast("the scene you chose, has no extension :(");
}
System.out.println("EXT " + FileExt);
File fileToUpload = new File(filePath);

How do I split the string at the file extension but also be able to handle and alert when the file has no extension.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sirvon
  • 2,547
  • 1
  • 31
  • 55
  • 3
    Consider using `lastIndexOf()`, with some heuristics to detect when it denotes an "extension" and when it's part of the filename. – laalto Jan 03 '14 at 13:39
  • 1
    See http://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java – Qtax Jan 03 '14 at 13:39
  • why don't reverse the string and take the first subString before the '.'? – Alessio Jan 03 '14 at 13:39
  • 1
    may be this link helps you http://stackoverflow.com/questions/4894885/how-to-check-file-extension-in-android – Meenal Jan 03 '14 at 13:50

7 Answers7

66

You can try this

int i = s.lastIndexOf(c);
String[] a =  {s.substring(0, i), s.substring(i)};
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
34

It might be easier to just assume that files which end with a dot followed by alphanumeric characters have extensions.

int p=filePath.lastIndexOf(".");
String e=filePath.substring(p+1);
if( p==-1 || !e.matches("\\w+") ){/* file has no extension */}
else{ /* file has extension e */ }

See the Java docs for regular expression patterns. Remember to escape the backslash because the pattern string needs the backslash.

user1537366
  • 1,100
  • 1
  • 9
  • 15
  • 1
    The \w metacharacter is used to find a word character http://www.w3schools.com/jsref/jsref_regexp_wordchar.asp – Alessio Jan 03 '14 at 15:28
  • Note that this will fail on files whose names start with a dot and don't have an extension (e.g. `.gitignore`), which are pretty commonplace on POSIX-based systems. This can be fixed by changing the `if` condition to check if `p` is less than _or_ equal to zero. – Mac Dec 13 '19 at 00:10
6

Is this Java? If so, why don't you use "java.io.File.getName".

For example:

File f = new File("/aaa/bbb/ccc.txt");
System.out.println(f.getName());

Out:

ccc.txt
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43
  • 4
    too expensive to build a File object just to parse the name – Jasmeet Singh Jul 13 '17 at 16:22
  • seriously @jasmeet? Files don't do anything under the covers except parse the name; some methods you may call on them might be expensive, but the constructor is pretty cheap. – John Calcote Mar 12 '21 at 02:19
  • This should be the accepted answer. You can also call f.getParent() to get the path portion. – John Calcote Mar 12 '21 at 02:20
  • 1
    No, this should definitely not be the accepted answer, read the first line in the question: "I'm basically trying to split a string on the last period to capture the file extension." – h00ligan Oct 11 '21 at 14:25
3

You can use a positive lookahead in your regex to ensure it only splits on the last occurrence. The positive lookahead ensures that it only splits when it does not see another occurrence later in the string.

// Using example filePath from question
String filePath = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
String[] parts = filePath.split("\\.(?=[^.]*$)");
// parts = [
//     "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped)"
//     "mp3"
// ]

Breaking down the regex:

  • \\. - Find a period
  • (?=[^.]*$) - make sure everything after is not a period, without including it in the match)
Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
2

You can use StringUtils from apache commons, which is an elegant way of extracting file type.

    String example = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
    String format = StringUtils.substringAfterLast(example, ".");
    System.out.println(format);

Program will print "mp3" in the console.

ar10a
  • 21
  • 3
1

How about splitting the filPath using the period as separator. And taking the last item in that array to get the extension:

        String fileTypeArray[] = filePath.split(",");
        String fileType = "";
        if(fileTypeArray != null && fileTypeArray.length > 0) {
          fileType = fileTypeArray[fileTypeArray.length - 1];
        }
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

For an arbitrary splitting string c of any length:

int i = s.lastIndexOf(c); 
String[] a =  {s.substring(0, i), s.substring(i+c.length())};
Jose Duarte
  • 129
  • 1
  • 6