Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change file extension at runtime in Java

I am trying to implement program to zip and unzip a file. All I want to do is to zip a file (fileName.fileExtension) with name as fileName.zip and on unzipping change it again to fileName.fileExtension.

like image 878
rahul0789 Avatar asked Aug 31 '12 06:08

rahul0789


People also ask

How do I get the file extension of a file in Java?

java“. The method getExtension(String) will check whether the given filename is empty or not. If filename is empty or null, getExtension(String filename) will return the instance it was given. Otherwise, it returns extension of the filename.


1 Answers

This is how I used to rename files or change its extension.

public static void modify(File file) 
    {
        int index = file.getName().lastIndexOf(".");
        //print filename
        //System.out.println(file.getName().substring(0, index));
        //print extension
        //System.out.println(file.getName().substring(index));
        String ext = file.getName().substring(index);
        //use file.renameTo() to rename the file
        file.renameTo(new File("Newname"+ext));
    }

edit: John's method renames the file (keeping the extension). To change the extension do:

public static File changeExtension(File f, String newExtension) {
  int i = f.getName().lastIndexOf('.');
  String name = f.getName().substring(0,i);
  return new File(f.getParent(), name + newExtension);
}

This changes only the last extension to a filename, i.e. the .gz part of archive.tar.gz. Therefore it works fine with Linux hidden files, for which the name starts with a . This is quite safe because if getParent() returns null (i.e. in the event of the parent being the system root) it is "cast" to an empty String as the whole argument to the File constructor is evaluated first.

The only case where you will get a funny output is if you pass in a File representing the system root itself, in which case the null is prepended to the rest of the path string.

like image 94
John Avatar answered Sep 29 '22 21:09

John