How to change file extension at runtime in Java

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

+7
source share
5 answers

Try:

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 } 
+5
source

So I renamed files or changed their 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: the John method renames the file (while preserving 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 the file name, i.e. the .gz part of archive.tar.gz . Therefore, it works great with hidden Linux files, for which the name begins with . This is completely safe, because if getParent() returns null (that is, getParent() when the parent is the system root), it is "cast" to an empty string, since the entire argument to the File constructor is evaluated first.

The only time you get funny output is if you pass a File representing the system root itself, in which case null will be added before the rest of the path line.

+5
source

I would check if the file has an extension before changing. The solution below also works with files without an 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"))); } 
+3
source
 FilenameUtils.getFullPathNoEndSeparator(doc.getDocLoc()) + "/" + FilenameUtils.getBaseName(doc.getDocLoc()) + ".xml" 
0
source

By the same logic as the mentioned @hsz, but instead just use the 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)); 
0
source

Source: https://habr.com/ru/post/924243/


All Articles