当前位置: 首页 > news >正文

java读取文件夹下所有文件并替换文件每一行中指定的字符串

【轉載】https://www.cnblogs.com/snake-hand/p/3157260.html

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

public class ChangeFile {
public static void main(String[] args) {
try {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:/EntNatureDistributionDAO.txt"))));//数据流读取文件

        StringBuffer strBuffer = new StringBuffer();
        String empty = "";
        String tihuan = "";
        for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
            if(temp.indexOf("/*") != -1 && temp.indexOf("*/") != -1){ //判断当前行是否存在想要替换掉的字符 -1表示存在
                tihuan = temp.substring(0, 10);
                temp = temp.replace(tihuan, empty);//替换为你想要的东东
            }
            strBuffer.append(temp);
            strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割
        }
        bufReader.close();
        PrintWriter printWriter = new PrintWriter("E:/EntNatureDistributionDAO.txt");//替换后输出的文件位置
        printWriter.write(strBuffer.toString().toCharArray());
        printWriter.flush();
        printWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

适用:如服务器崩溃 导致文件丢失,还原后类文件在每一行的开头都加了很多注释(如下)

/* / package com.itown.iesap.starquery.dao;
/
/
/
/ import com.itown.framework.impl.ThreadContext;
/
*/ import com.itown.framework.persistence.AbstractDao;
.........很多很多.....

替换之后就是这样的:

package com.itown.iesap.starquery.dao;

import com.itown.framework.impl.ThreadContext;
import com.itown.framework.persistence.AbstractDao;
.........很多很多......

如果你又成百上千个这样的文件替换那就要读取文件夹下的所有文件:

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

public class ChangeFile {
public static void main(String[] args) {
try {
//读取指定文件夹下的所有文件
String filepath = "D:/AOE/abc/";//给我你的目录文件夹路径
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("---------- 该文件不是一个目录文件 ----------");
} else if (file.isDirectory()) {
System.out.println("---------- 很好,这是一个目录文件夹 ----------");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\" + filelist[i]);
//String path = readfile.getPath();//文件路径
String absolutepath = readfile.getAbsolutePath();//文件的绝对路径
String filename = readfile.getName();//读到的文件名
开始挨个的读取文件
BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(absolutepath)));//数据流读取文件
StringBuffer strBuffer = new StringBuffer();
String empty = "";
String tihuan = "";
for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
if(temp.indexOf("/") != -1 && temp.indexOf("/") != -1){ //判断当前行是否存在想要替换掉的字符 -1表示存在
tihuan = temp.substring(0, 9);//这里截取多长自己改
temp = temp.replace(tihuan, empty);//替换为你想要的东东
}
strBuffer.append(temp);
strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割
}
bufReader.close();
PrintWriter printWriter = new PrintWriter("E:/ttt/"+filename);//替换后输出的文件位置(切记这里的E:/ttt 在你的本地必须有这个文件夹)
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
System.out.println("ok 第 " + (i+1) +" 个文件操作成功!");
读取兵输出一个文件结束
}
System.out.println("---------- 所有文件操作完毕 ----------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

这样更加清晰明了些:

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

public class ReadFile {

/**
 * 主方法测试
 * @param args 
 * @author 杜文俊
 * @update 2013-6-26 下午1:36:31
 */
public static void main(String[] args) {
    String filePath = "D:/AOE/abc/"; //给我你要读取的文件夹路径
    File outPath = new File("E:/AOE/abc/"); //随便给一个输出文件夹的路径(不存在也可以)
    readFolder(filePath,outPath);
}

/**
 * 读取文件夹
 * @return 
 */
public static void readFolder(String filePath,File outPath){
    try {
        //读取指定文件夹下的所有文件
        File file = new File(filePath);
        if (!file.isDirectory()) {
            System.out.println("---------- 该文件不是一个目录文件 ----------");
        } else if (file.isDirectory()) {
            System.out.println("---------- 很好,这是一个目录文件夹 ----------");
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filePath + "\\" + filelist[i]);
                //String path = readfile.getPath();//文件路径
                String absolutepath = readfile.getAbsolutePath();//文件的绝对路径
                String filename = readfile.getName();//读到的文件名
                readFile(absolutepath,filename,i,outPath);//调用 readFile 方法读取文件夹下所有文件
            }
            System.out.println("---------- 所有文件操作完毕 ----------");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 读取文件夹下的文件
 * @return 
 */
public static void readFile(String absolutepath,String filename,int index,File outPath){
    try{
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(absolutepath)));//数据流读取文件
        StringBuffer strBuffer = new StringBuffer();
        String empty = "";
        String tihuan = "";
        for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
            if(temp.indexOf("/*") != -1 && temp.indexOf("*/") != -1){ //判断当前行是否存在想要替换掉的字符 -1表示存在
                tihuan = temp.substring(0, 9);//这里截取多长自己改
                temp = temp.replace(tihuan, empty);//替换为你想要的东东
            }
            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);//替换后输出的文件位置(切记这里的E:/ttt 在你的本地必须有这个文件夹)
        printWriter.write(strBuffer.toString().toCharArray());
        printWriter.flush();
        printWriter.close();
        System.out.println("第 " + (index+1) +" 个文件   "+ absolutepath +"  已成功输出到    " +outPath+"\\"+filename);
    }catch(Exception e){
        e.printStackTrace();
    }
}

}

转载于:https://www.cnblogs.com/Andrew520/p/8196524.html

相关文章:

  • 6.2. group by
  • 纪念第一次在博客园的书写
  • 第二次冲刺站立会议(7)
  • python学习笔记(八):异常处理
  • python中package机制的两种实现方式
  • 2017年年度总结
  • 原来Intel CPU漏洞是它引起的!
  • 在全是无人车的世界里,过马路是种怎样的体验?
  • DeepMind新论文:基于变分方法的自编码生成对抗网络
  • document.getElementByName() 获取值得问题
  • Python3虚拟环境--venv
  • 管理控制文件 和日志文件
  • Fedora 全局代理上网设置
  • Eclipse Tomcat启动后乱码
  • 设置IntelliJ主题和字体方法
  • 230. Kth Smallest Element in a BST
  • Github访问慢解决办法
  • JavaWeb(学习笔记二)
  • Joomla 2.x, 3.x useful code cheatsheet
  • Linux快速复制或删除大量小文件
  • MySQL用户中的%到底包不包括localhost?
  • Node项目之评分系统(二)- 数据库设计
  • opencv python Meanshift 和 Camshift
  • STAR法则
  • UMLCHINA 首席专家潘加宇鼎力推荐
  • v-if和v-for连用出现的问题
  • 产品三维模型在线预览
  • 前端面试之CSS3新特性
  • 使用 Node.js 的 nodemailer 模块发送邮件(支持 QQ、163 等、支持附件)
  • 小而合理的前端理论:rscss和rsjs
  • 协程
  • 走向全栈之MongoDB的使用
  • mysql面试题分组并合并列
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • # 透过事物看本质的能力怎么培养?
  • #DBA杂记1
  • #laravel 通过手动安装依赖PHPExcel#
  • (二)Eureka服务搭建,服务注册,服务发现
  • (附源码)spring boot儿童教育管理系统 毕业设计 281442
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (原创) cocos2dx使用Curl连接网络(客户端)
  • (转)Linux整合apache和tomcat构建Web服务器
  • ***微信公众号支付+微信H5支付+微信扫码支付+小程序支付+APP微信支付解决方案总结...
  • **PHP分步表单提交思路(分页表单提交)
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .Net 4.0并行库实用性演练
  • .net core 6 redis操作类
  • .Net CoreRabbitMQ消息存储可靠机制
  • .NET成年了,然后呢?
  • .Net接口调试与案例
  • .Net小白的大学四年,内含面经
  • @Async注解的坑,小心
  • @Autowired多个相同类型bean装配问题