主要涉及的类和方法
类
java.io.File
方法
- exist()
- creatNewFile()
- getName()
- getParent()
- renameTo(File dest)
关于构造方法
File(String parent, String child)
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");
}
}
}