Rename a file using Java

前端 未结 14 818
感情败类
感情败类 2020-11-22 07:54

Can we rename a file say test.txt to test1.txt ?

If test1.txt exists will it rename ?

How do I rename it to the alrea

相关标签:
14条回答
  • 2020-11-22 08:02

    Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

    import java.util.Arrays;
    import java.util.List;
    
    public class FileRenameUtility {
    public static void main(String[] a) {
        System.out.println("FileRenameUtility");
        FileRenameUtility renameUtility = new FileRenameUtility();
        renameUtility.fileRename("c:/Temp");
    }
    
    private void fileRename(String folder){
        File file = new File(folder);
        System.out.println("Reading this "+file.toString());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            List<File> filelist = Arrays.asList(files);
            filelist.forEach(f->{
               if(!f.isDirectory() && f.getName().startsWith("Old")){
                   System.out.println(f.getAbsolutePath());
                   String newName = f.getAbsolutePath().replace("Old","New");
                   boolean isRenamed = f.renameTo(new File(newName));
                   if(isRenamed)
                       System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
                   else
                       System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
               }
            });
    
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 08:03

    Try This

    File file=new File("Your File");
    boolean renameResult = file.renameTo(new File("New Name"));
    // todo: check renameResult
    

    Note : We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.

    0 讨论(0)
  • 2020-11-22 08:03

    As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

    About renaming a file in Java, see the documentation for the renameTo() method in class File.

    0 讨论(0)
  • 2020-11-22 08:03
    Files.move(file.toPath(), fileNew.toPath()); 
    

    works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

    0 讨论(0)
  • 2020-11-22 08:05

    Here is my code to rename multiple files in a folder successfully:

    public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
        if(newName == null || newName.equals("")) {
            System.out.println("New name cannot be null or empty");
            return;
        }
        if(extension == null || extension.equals("")) {
            System.out.println("Extension cannot be null or empty");
            return;
        }
    
        File dir = new File(folderPath);
    
        int i = 1;
        if (dir.isDirectory()) { // make sure it's a directory
            for (final File f : dir.listFiles()) {
                try {
                    File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);
    
                    if(f.renameTo(newfile)){
                        System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                    } else {
                        System.out.println("Rename failed");
                    }
                    i++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    and run it for an example:

    renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
    
    0 讨论(0)
  • 2020-11-22 08:07

    Running code is here.

    private static void renameFile(File fileName) {
    
        FileOutputStream fileOutputStream =null;
    
        BufferedReader br = null;
        FileReader fr = null;
    
        String newFileName = "yourNewFileName"
    
        try {
            fileOutputStream = new FileOutputStream(newFileName);
    
            fr = new FileReader(fileName);
            br = new BufferedReader(fr);
    
            String sCurrentLine;
    
            while ((sCurrentLine = br.readLine()) != null) {
                fileOutputStream.write(("\n"+sCurrentLine).getBytes());
            }
    
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
                if (br != null)
                    br.close();
    
                if (fr != null)
                    fr.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题