文件和文件目录重命名问题
2015-08-27 12:43
253 查看
不多说,直接贴例子
/**
* 重命名文件名,新文件名不加后缀
* @param filePath
* @param newName
*/
public static void rename(String filePath,String newName){
File file=new File(filePath);
if(!file.isDirectory()&&filePath.indexOf(".")!=-1){
String suffix=filePath.substring(filePath.lastIndexOf(".")+1,filePath.length());
newName=filePath.substring(0, filePath.lastIndexOf("/"))+newName+suffix;
}else{
//对目录进行处理
String str;
if(filePath.lastIndexOf("/")==filePath.length()-1){
str=filePath.substring(0, filePath.length()-1);
}else{
str=filePath;
}
//截取当前文件目录名
int index=str.lastIndexOf("/");
String fileName=str.substring(index+1,str.length());
//替换项目名为commonWeb的名字
newName=filePath.replace(fileName,newName);
}
file.renameTo(new File(newName));
}
这里的newName最终要是一个路径,而不是一个文件名,之前因为只写文件名,所以一直不成功。
/**
* 重命名文件名,新文件名不加后缀
* @param filePath
* @param newName
*/
public static void rename(String filePath,String newName){
File file=new File(filePath);
if(!file.isDirectory()&&filePath.indexOf(".")!=-1){
String suffix=filePath.substring(filePath.lastIndexOf(".")+1,filePath.length());
newName=filePath.substring(0, filePath.lastIndexOf("/"))+newName+suffix;
}else{
//对目录进行处理
String str;
if(filePath.lastIndexOf("/")==filePath.length()-1){
str=filePath.substring(0, filePath.length()-1);
}else{
str=filePath;
}
//截取当前文件目录名
int index=str.lastIndexOf("/");
String fileName=str.substring(index+1,str.length());
//替换项目名为commonWeb的名字
newName=filePath.replace(fileName,newName);
}
file.renameTo(new File(newName));
}
这里的newName最终要是一个路径,而不是一个文件名,之前因为只写文件名,所以一直不成功。
相关文章推荐
- 10个加速Table Views开发的Tips
- Oracle(一)--> 数据库对象详解(文字解释,先有个小理解~)
- 黑马程序员—————Java基础--------IO流
- OpenGL ES渲染管线与着色器
- 职场规划从“试错”开始
- [LeetCode#72]Edit Distance
- Android px pt dp sp...
- c++中的字符串与数字相互转换
- 删除用户的时候,产生“数据库主体在该数据库中拥有架构,无法删除”的解决办法
- 深度学习(DL)与卷积神经网络(CNN)学习笔记随笔-02-基于Python的卷积运算
- RedisUtil
- 项目源代码目录结构建议
- 张益唐:我的数学人生
- 使用#pragma阻止一些warnings
- 安装及使用YUICompressor(压缩JS,CSS文件)4
- WinForm实现窗体最大化并遮盖任务栏的方法
- Robot Framework 教程 (6) - 使用条件表达式
- 解决cocos2d-x 安卓锁屏再解锁,OPenGL报错;后台转前台异常问题解决办法 (续)
- SDN相关组织之ODL(opendaylight)
- 文本检查点