1

Here I input a string where user inputs filename with extension and i want to write a program that gives out the extension of the file but when I run this program it gives exception arrayindexoutofbound exception, any reason why?

import java.util.Scanner;

public class Extensionfile {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter file with data type");
        String file = sc.next();
        String parts[] = file.split(".");
        String part1 = parts[1];
        System.out.println("The file type is"+part1);

    }
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • 1
    `file.split("\\.");` `.` is any character in regex. And after that check if you have atleast one element in `parts` – jmj Jul 22 '18 at 04:37
  • 1
    [`FilenameUtils.getExtension(String)`](http://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getExtension%28java.lang.String%29) – Elliott Frisch Jul 22 '18 at 04:42
  • This code has a bug. Filenames themselves can contain periods – OneCricketeer Jul 22 '18 at 04:46

1 Answers1

6

Since period . is predefined character class in java regular expressions, you should use in below way

String parts[] = file.split("\\.");

or

String parts[] = file.split("[.]");

check here for more information here

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98