1.从文件中读取字符串
2.读取每一行
3.将每一行中的某两个字符串之间的字符串截取并保存
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class ReadAndGet3{
public static void main(String[] args){
File in=new File("C:\\Users\\Administrator\\Desktop\\1.txt"); //读入的文件
File out = new File("C:\\Users\\Administrator\\Desktop\\2.txt"); //写入的文件
String startStr="</";//开始的字符串
String endStr=">";//结束字符串
int startIndex=0;//开始的字符串
int endIndex=0;//结束字符串
FileWriter fw = null;
BufferedWriter writer = null;
BufferedReader reader=null;
String temp=null;
int line=0;
try{
reader=new BufferedReader(new FileReader(in)); //读入
//清空文件内容
if(!out.exists()) {
out.createNewFile();
}
FileWriter fileWriter =new FileWriter(out);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
while((temp=reader.readLine())!=null){
startIndex=temp.indexOf(startStr)+startStr.length();
endIndex=temp.lastIndexOf(endStr)+endStr.length()-1;
if(temp.contains(startStr)&&temp.contains(endStr)&&startIndex<endIndex){
//判断当前行是否包含开始结束字符串,并且结束位置在开始之后
String ss = temp.substring(startIndex, endIndex);//截取字符串
//写入文件
fw = new FileWriter(out, true);
writer = new BufferedWriter(fw);
writer.write(ss+"\r\n");
writer.close();
}
line++;
}
System.out.println("共有"+line+"行");
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
测试示例
输入文件
<123>
<456>
efefe>
fefe<789>dcdvc
输出文件
123
456
789