Use the following code, all *.txt will be changed
登录 | 论坛导航 -> 华新鲜事 -> 社会百科 | 本帖共有 1 楼,分 1 页, 当前显示第 1 页 : 本帖树形列表 : 刷新 : 返回上一页
<<始页  [1]  末页>>
作者:天下 (等级:7 - 出类拔萃,发帖:703) 发表:2003-01-21 12:02:53  楼主  关注此帖评分:
how to use java program to...rename all files in a directory according to a certain pattern, for example, 1.txt 2.txt 3.txt 4.txt . . .
Use the following code, all *.txt will be changed
to *.new (tested in UNIX)


import java.io.*;

public class temp{
public static void main(String[] args){
File f = new File(".");
File[] children = f.listFiles();
for (int i=0;i<children.length;i++){
String name = children[i].getName();
if (children[i].getName().endsWith(".txt")){
name = name.replaceAll(".txt",".new");
File f1 = new File(name);
children[i].renameTo(f1);
}
}
}
}


Things to note:
1. Directory is reprensented by class File. I used current directory (.), you can supply absolute path of the directory where you want to rename files.
2. Use listFiles to get all files in that directory.
3. I used some string methods to manipulate the file name.
4. You need to create a new File object and pass it to the method renameTo to change the name.

Hope this can help ....
俯首仰看娥眉细,何曾折腰觅封侯?
欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!原文 / 传统版 / WAP版所有回复从这里展开收起列表
论坛导航 -> 华新鲜事 -> 社会百科 | 返回上一页 | 本主题共有 1 篇文章,分 1 页, 当前显示第 1 页 | 回到顶部
<<始页  [1]  末页>>

请登录后回复:帐号   密码