How to change file extension at runtime in Java

2020-02-05 20:16发布

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.

6条回答
地球回转人心会变
2楼-- · 2020-02-05 20:47

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 only changes the last extension to a filename, i.e. the .gz part of archive.tar.gz. Therfore 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.

查看更多
一夜七次
3楼-- · 2020-02-05 20:58
FilenameUtils.getFullPathNoEndSeparator(doc.getDocLoc()) + "/" +
     FilenameUtils.getBaseName(doc.getDocLoc()) + ".xml"
查看更多
别忘想泡老子
4楼-- · 2020-02-05 21:00

I would check, if the file has an extension before changing. The solution below works also with files without extension or multiple extensions

public File changeExtension(File file, String extension) {
    String filename = file.getName();

    if (filename.contains(".")) {
        filename = filename.substring(0, filename.lastIndexOf('.'));
    }
    filename += "." + extension;

    file.renameTo(new File(file.getParentFile(), filename));
    return file;
}

@Test
public void test() {
    assertThat(changeExtension(new File("C:/a/aaa.bbb.ccc"), "txt"), 
                            is(new File("C:/a/aaa.bbb.txt")));

    assertThat(changeExtension(new File("C:/a/test"), "txt"), 
                            is(new File("C:/a/test.txt")));
}
查看更多
Animai°情兽
5楼-- · 2020-02-05 21:01

Try with:

File file  = new File("fileName.zip"); // handler to your ZIP file
File file2 = new File("fileName.fileExtension"); // destination dir of your file
boolean success = file.renameTo(file2);
if (success) {
    // File has been renamed
}
查看更多
太酷不给撩
6楼-- · 2020-02-05 21:02

I want to avoid the new extension just happening to be in the path or filename itself. I like a combination of java.nio and apache StringFilenameUtils.

public void changeExtension(Path file, String extension) throws IOException {
    String newFilename = FilenameUtils.removeExtension(file.toString()) + EXTENSION_SEPARATOR_STR + extension;
    Files.move(file, Paths.get(newFilename, StandardCopyOption.REPLACE_EXISTING));
}
查看更多
做个烂人
7楼-- · 2020-02-05 21:06

By the same logic as mentioned @hsz, but instead simply use replacement:

File file  = new File("fileName.fileExtension"); // creating object of File 
String str = file.getPath().replace(".fileExtension", ".zip"); // replacing extension to another 
file.renameTo(new File(str)); 
查看更多
登录 后发表回答