Question: How to split String if it contains period symbol (.) in between?
Problem:I have to write a program which takes file name with any extension as a parameter and it should return the extension of that file.
For Example:
If input parameters are as:
input_1 = testdata.properties
input_2 = userList.xlsx
Output would be:
output_1 = .properties
output_2 = .xlsx
Code Snippet:
Currently, I am using split() function with the regular expression ("."), of String class to achieve this as mentioned below:
String fileExt = getExtenstion("testdata.properties");
System.out.println("Extension of File : "+fileExt);
public String getExtension(String fileName)
{
String tempArray[] = fileName.split(".");
String fileExt = tempArray[1];
return fileExt;
}
When I executed this program I got, "ArrayIndexOutOfBoundsException" for yellow highlighted line of code as mentioned above.
Please help me out to get this code corrected. Thanks in advance.
Please do comment and share the post with your friends and colleagues. For any query or question, you can also mail me at ashu.kumar940@gmail.com.
Other Blogs:
Hi,
ReplyDeleteIn the section "String tempArray[] = fileName.split(".")" need to add '//'. So the code will be as below-
public String getExtension(String fileName)
{
String tempArray[] = fileName.split("//.");
String fileExt = tempArray[1];
return fileExt;
}
Hi Akshay,
DeleteYou are very close. I think you mistakenly write '//' in the above code. Actually, we have to use "\\" symbol instead. Because whenever I tried to run above code I got, "ArrayIndexOutOfBoundsException" error again. Please recheck your code.
Correct Code:
String tempArray[] = fileName.split("\\.");
Here is the correct and code without any error or exception:
ReplyDeleteString fileExt = getExtenstion("testdata.properties");
System.out.println("Extension of File : "+fileExt);
public String getExtension(String fileName)
{
String tempArray[] = fileName.split(".");
String fileExt = tempArray[1];
return fileExt;
}