Java File Rename renameFile(String newName, String oldName)

Here you can find the source of renameFile(String newName, String oldName)

Description

rename File

License

Open Source License

Declaration

static public void renameFile(String newName, String oldName) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

public class Main {
    static public void renameFile(String newName, String oldName) throws IOException {
        if (File.separatorChar == '\\') {
            copyFile(oldName, newName);//from w  ww . j  ava2s  .co  m
            File oldF = new File(oldName);
            oldF.delete();
        } else {
            File oldF = new File(oldName);
            File newF = new File(newName);
            if (newF.exists()) {
                newF.delete();
            }
            if (!oldF.renameTo(newF)) {
                throw new IOException(String.format("Unable to rename %s to %s", oldName, newName));
            }
        }
    }

    static public void copyFile(String src, String dst) throws IOException {
        FileOutputStream fos = null;
        FileInputStream fis = null;

        try {
            fos = new FileOutputStream(dst);
            fis = new FileInputStream(src);
            byte[] buf = new byte[4096];

            int nread = fis.read(buf);
            while (nread > 0) {
                fos.write(buf, 0, nread);
                nread = fis.read(buf);
            }
        } catch (IOException e) {
            File f = new File(dst);
            if (f.exists()) {
                f.delete();
            }

            throw e;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                }
            }
        }
    }

    static public boolean exists(String path) {
        File f = new File(path);
        return f.exists();
    }
}

Related

  1. renameFile(String fileFrom, String fileTo)
  2. renameFile(String fileName, String destFilename)
  3. renameFile(String filePath, String descFilePath)
  4. renameFile(String from, String to, String baksuffix)
  5. renameFile(String fromFilename, String toFilename)
  6. renameFile(String oldFile, String newName)
  7. renameFile(String oldFileName, String newFileName)
  8. renameFile(String oldname, String newname)
  9. renameFile(String oldname, String newname)