java 修改文件某行内容

1、原始文件见下图,insert into 后没有表名,sql无法执行。如需执行,就得替换空串,加入表名

java 修改文件某行内容

 2、处理程序

public class ProcessData {       
    public String readFileContent(String filePath) {  
        BufferedReader br = null;  
        String line = null;  
        StringBuffer bufAll = new StringBuffer();  //保存修改过后的所有内容,不断增加         
        try {            
            br = new BufferedReader(new FileReader(filePath));              
            while ((line = br.readLine()) != null) {  
                StringBuffer buf = new StringBuffer();  
              //修改内容核心代码
                if (line.startsWith("INSERT INTO")) {  
                   buf.append(line);
                   buf.replace(12, 14, "lf");
                   buf.append(System.getProperty("line.separator"));
                   bufAll.append(buf);
                }  
          
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                }  
            }  
        }  
        return bufAll.toString();  
    }        
   //写回文件
    public void writeFile(String filePath, String content) {  
        BufferedWriter bw = null;  
          
        try {           
            bw = new BufferedWriter(new FileWriter(filePath));     
            bw.write(content);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bw != null) {  
                try {  
                    bw.close();  
                } catch (IOException e) {  
                    bw = null;  
                }  
            }  
        }  
    }     

    public static void main(String[] args) {  
        String filePath = "D:/data_lf.sql";
        ProcessData processData = new ProcessData();  
        processData.writeFile(filePath, processData.readFileContent(filePath));        
    }    
}

3、处理后的文件

java 修改文件某行内容