JAVA修改文件名

主要涉及的类和方法

java.io.File

方法

  • exist()
  • creatNewFile()
  • getName()
  • getParent()
  • renameTo(File dest)

关于构造方法

  1. File(String parent, String child)
  2. File(String pathname)

File newFile = new File(file + File.separator + style , originName);
两参数的File构造方法,逗号前卫路径,逗号后卫文件名,执行后自动加上分隔符,否则路径分隔需要用到File.separtor

DirRename.java
执行结果:
D:\li\1218\url2.txt

代码

参考代码 (有改动)

FileRename.java

package com.lee.test;

import java.io.File;

public class Rename
{
    public static void main(String[] args) throws Exception
    {
        File oldFile = new File("D:/url.txt");

        if(!oldFile.exists())
        {
            oldFile.createNewFile();
        }

        System.out.println("当前修改的文件名是:" + oldFile.getName());

        String rootPath = oldFile.getParent();

        //File f2 = new File(path + File.pathSeparator + "url2.txt");

        File newFile = new File(rootPath, "newurl.txt");

        if(oldFile.renameTo(newFile))
        {
            System.out.println("Success!");
        }
        else
        {
            System.out.println("fail");
        }                       

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值