天天看点

java修改文件名

public void renameFile(String oldFile, String newFile) {

  HttpServletRequest request = ServletActionContext.getRequest();

  String path =  request.getSession().getServletContext().getRealPath("/");

  String updatePath = path+"upload"+File.separator;

        File oldfile = new File(updatePath+oldFile);

        //检查要重命名的文件是否存在,是否是文件

        if (!oldfile.exists() || !oldfile.isDirectory()) {

            System.out.println("File does not exist: " + oldFile);

            return;

        }

        File newfile = new File(updatePath+newFile);

        //修改文件名

        if (oldfile.renameTo(newfile)) {

            System.out.println("File has been renamed.");

        } else {

            System.out.println("Error renmaing file");

    }