How to change file extension at runtime in Java

前端 未结 6 594
囚心锁ツ
囚心锁ツ 2021-01-04 07:42

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

6条回答
  •  我在风中等你
    2021-01-04 08:23

    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")));
    }
    

提交回复
热议问题