java rename file extension

Solutions on MaxInterview for java rename file extension by the best coders in the world

showing results for - "java rename file extension"
Richard
29 Oct 2020
1// java rename file extension
2import java.io.File;
3import java.io.IOException;
4import java.util.regex.Matcher;
5import java.util.regex.Pattern;
6public class RenameFileExtension 
7{
8   public static boolean renameExtension(String strSource, String strNewExtension)
9   {
10      String target;
11      String strCurrent = findExtension(strSource);
12      if(strCurrent.equals(""))
13      {
14         target = strSource + "." + strNewExtension;
15      }
16      else 
17      {
18         target = strSource.replaceFirst(Pattern.quote("." + strCurrent) + "$",Matcher.quoteReplacement("." + strNewExtension));
19      }
20      return new File(strSource).renameTo(new File(target));
21   }
22   public static String findExtension(String strFile) 
23   {
24      String strExtension = "";
25      int a = strFile.lastIndexOf('.');
26      if(a > 0 &&  a < strFile.length() - 1) 
27      {
28         strExtension = strFile.substring(a + 1);
29      }
30      return strExtension;
31   }
32   public static void main(String[] args) throws IOException 
33   {
34      System.out.println(RenameFileExtension.renameExtension("A:\\java.txt", "pdf"));
35   }
36}