修改文件夹名称和文件名

package hgweb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Test {
/**
* @author itmyhome
*/
public static void main(String[] args) {
File f = new File(“F:/wuyao”);
print(f, 0);
}

/** 
 * 遍历文件夹 
 * 
 * @param f 
 * @param len 
 */  
public static void print(File f, int len) {  
    File[] file = f.listFiles();  

    for (int i = 0; i < file.length; i++) {  
        if (file[i].isDirectory()) { //判断是否文件夹  
            print(file[i], len + 1);  
        }  

        // 为防止输出文件覆盖源文件,所以更改输出盘路径 也可自行设置其他路径  
        File outPath = new File(file[i].getParent().replace("F:", "E:").replace("wuyao", "huzhu")); 


        File readfile = new File(file[i].getAbsolutePath());  

        if (!readfile.isDirectory()) {  
            String filename = readfile.getName(); // 读到的文件名  
            String absolutepath = readfile.getAbsolutePath(); // 文件的绝对路径  
            readFile(absolutepath, filename, i, outPath); // 调用 readFile  
        }  
    }  
}  

/** 
 * 读取文件夹下的文件 
 * 
 * @return 
 */  
public static void readFile(String absolutepath, String filename,  
    int index, File outPath) {  
    try {  
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(  
                    new FileInputStream(absolutepath), "gb2312")); // 数据流读取文件  

        StringBuffer strBuffer = new StringBuffer();  
        String newStr = "huzhu";  
        String oldStr = "wuyao";  

        for (String temp = null; (temp = bufReader.readLine()) != null;  
                temp = null) {  
            if ((temp.indexOf(oldStr) != -1) &&  
                    (temp.indexOf(oldStr) != -1)) { // 判断当前行是否存在想要替换掉的字符  
                temp = temp.replace(oldStr, newStr); // 此处进行替换  
            }  

            strBuffer.append(temp);  
            strBuffer.append(System.getProperty("line.separator")); // 换行符  
        }  

        bufReader.close();  

        if (outPath.exists() == false) { // 检查输出文件夹是否存在,若不存在先创建  
            outPath.mkdirs();  
            System.out.println("已成功创建输出文件夹:" + outPath);  
        }  

        PrintWriter printWriter = new PrintWriter(outPath + "\\" +  
                filename, "gb2312"); // 替换后输出文件路径  
        printWriter.write(strBuffer.toString().toCharArray()); //重新写入  
        printWriter.flush();  
        printWriter.close();  
        System.out.println("第 " + (index + 1) + " 个文件   " + absolutepath +  
            "  已成功输出到    " + outPath + "\\" + filename);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

}

你可能感兴趣的:(JAVA,java)