当前位置:编程学习 > JAVA >>

用java实现部分文件读取与替换

public static void main(String[] args) {
try {
String content = "<body><h1><font color='red'>中国</font></h1></body>";
 test6(url, "d:/a.html", content);
/*System.out.println("======="
+ content.subSequence(0, content.length() - 7));
System.out.println(content.subSequence(content.length() - 7,
content.length()));
int startIndex = content.lastIndexOf("</body>");

System.out
.println("======2====" + content.substring(0, startIndex));*/
} catch (Exception e) {
e.printStackTrace();
}
}

///////////////////////////

public static void test6(String path, String path1, String newContent) {
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String node = null;
StringBuffer buffer = new StringBuffer();
System.out.println("=================原始文件html内容==============");
while ((node = br.readLine()) != null) {
buffer.append(node);
}
int startIndex = buffer.indexOf("<body>");
int endIndex = buffer.lastIndexOf("</body>");
if (startIndex != -1 && endIndex != -1) {

StringBuffer str = buffer.replace(startIndex, endIndex,
newContent);
File file = new File(path1);
if (file.exists())
file.delete();
else
file.createNewFile();
FileWriter fileWriter = new FileWriter(path1);
fileWriter.write(str.toString());
fileWriter.flush();
fileWriter.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,