Advertisement

修改文件夹名称和文件名

阅读量:

package hgweb;

引入类java.io.BufferedReader;
引入文件类java.io.File;
引入FileInputStream类;
引入Reader类型中的BufferedReader类。

此为Test类。(注:此处可添加更多关于该类背景的信息)

此主方法为静态且无返回值。(注:可进一步描述其功能或作用)

创建文件对象f并初始化为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();  
    }  
    }

}

全部评论 (0)

还没有任何评论哟~