3
4

6 回答 6

8

You need to escape the dot:

String[] y=x.split("\\.");

Another solution is using String.lastIndexOf and String.substring as there is no need for regex.

于 2013-09-02T12:03:18.850 回答
6

You need to escape the dot, as it is a regex metacharacter:

String[] y = x.split("\\.");

Other possibilities are to use a character class

String[] y = x.split("[.]");

or use Pattern.quote() to do the necessary escaping for you.

String[] y = x.split(Pattern.quote("."));

Above is a fix for your code. A more reasonable solution to your problem would be

if (fileName.indexOf('.') != -1) {
    System.out.println("File is of type "+ x.substring(x.lastIndexOf('.') + 1));
    return true;
} else {
    System.out.println("Unknown File Extension");
    return false;
}

Beware of files like foo.tar.gz, where the filename is foo and the extion tar.gz also contains a dot.

于 2013-09-02T12:03:32.707 回答
1

You don't really regex for this job.

This code should work (without regex):

if (fileName.indexOf('.') > 0) {
    System.out.println("File is of type "+ filename.substring(filename.lastIndexOf('.')+1);
}
else {
    System.out.println("Unknown File Extension");
}
于 2013-09-02T12:05:08.117 回答
1
public Boolean FType() {
        String[] tokens = fileName.split("\\."); // Use regex
        if (tokens.length == 1) { // No dots
            System.err.println("Unknown File Extension");
            return false;
        }
        System.out.println("File is of type [" + tokens[tokens.length - 1] + "]");
        return true;
    }

You have to escape the "." character -> "\\."

This function split the fileName using "." and display the last token. So if the fileName is "test.something.doc", the result will be "doc".

于 2013-09-02T12:10:16.540 回答
1

In this case, following will give you out put as File is of type [File, doc] for File.doc

        String[] y=x.split("\\.");
        System.out.println("File is of type "+ Arrays.toString(y));

If you want to get extension only change your code as follows.

        String[] y=x.split("\\.");
        System.out.println("File is of type "+ y[1]);

But what happened if your file has name like my.File.doc? Then this way is not good. So it is better to use following.

    public static Boolean Ftype(String fileName) {
    if(fileName.lastIndexOf('.') != -1){
        String x= fileName.toString();
        String[] y=x.split("\\.");
        System.out.println("File is of type "+ y[y.length-1]);
        return true;
    }
    else
    {
        System.out.println("Unknown File Extension");
        return false;
    }
于 2013-09-02T12:15:40.510 回答
0

System.out.println("File is of type "+ y[y.length-1]);

于 2013-09-02T12:05:41.680 回答