import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
//File f = new File(fileTest.getDirPath());
//fileTest.showDir(f, 1);
//fileTest.delNullDir(f);
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4");
//fileTest.showDir(f, 1);
//fileTest.writeNameToTxt();
//System.out.println(f.getPath());//返回抽象路径名字符串;输入D:\android\新建文本文档.txt返回D:\android\新建文本文档.txt
//System.out.println(f.getParent());//返回D:\android
fileTest.changeFileName();
}
//转换路径
public String getDirPath(){
Scanner scan = new Scanner(System.in);
System.out.println("please input scn:");
String dir = scan.nextLine();
dir = dir.replace("\\","\\\\");
return dir;
}
//显示目录下的文件夹和文件;显示层级;将其写入文件;
public void showDir(File f,int count){
for(File file:f.listFiles()){
//输出层级:
System.out.print(count+".");
for(int i=0;i<count;i++){
System.out.print("|———");
}
System.out.println(file.getName());
if(file.isDirectory()){
showDir(file,count+1);
}
}
}
//删除空目录
public void delNullDir(File f){
for(File file:f.listFiles()){
if(file.isDirectory()){
if(file.listFiles().length == 0){
file.delete();
continue;
}
}
if(file.isDirectory())
delNullDir(file);
}
}
//将将目录下的所有文件夹名和文件名写入到txt中,调用writeToTxt1()方法!
public void writeNameToTxt(){
//获取一个目录
File f = new File(getDirPath());
//将写入到的txt
File writeTxt = new File("D:\\temp\\delNullDir.txt");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(writeTxt));
writeToTxt(f, 1,bw);
bw.flush();
bw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("写入完毕!");
}
//输入到文本
public void writeToTxt(File f,int count,BufferedWriter bw) {
for(File file:f.listFiles()){
try{
bw.write(count+".");
for(int i=0;i<count;i++){
bw.write("|——");
}
bw.write(file.getName());
bw.newLine();
}
catch(IOException e){
e.printStackTrace();
}
if(file.isDirectory()){
writeToTxt(file,count+1,bw);
}
}
}
//改变一个目录下文件的名称,如123.txt替换为223.txt
//获取目录-得到所有文件的一个list-for取出一个获取name-判断是否包含要替换的字符-有,替换-知道完成;
public void changeFileName(){
File f = new File(getDirPath());//获取一个目录
for(File file:f.listFiles()){
if(file.isFile()){
String fileName = file.getName();
if(fileName.indexOf("文")!= -1){
String newFileName = file.getParent()+"\\"+fileName.replaceAll("文", "刘伟");
if(!file.renameTo(new File(newFileName)))
System.out.println(newFileName+":命名失败,请查看是否已存在此文件名!");
}
}
}
}
}
http://blog.csdn.net/cw0504121/article/details/77862707