思路:首先读取文件内容,找到方法名后,然后追加内容。针对的是小文件处理方式。
String beanPath = System.getProperty("user.dir") + "/src/main/java/com/test.java";
try {
BufferedReader bufReader = new BufferedReader(
new InputStreamReader(new FileInputStream(new File(beanPath))));//数据流读取文件
StringBuffer strBuffer = new StringBuffer();
for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
strBuffer.append(temp);
strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割
if(temp.indexOf("test") != -1){//找到指定的方法
strBuffer.append("添加内容");//插入内容
strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割
}
}
bufReader.close();
PrintWriter printWriter = new PrintWriter(beanPath);//替换后输出的文件位置
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}