截取两个字符串中的字符串

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值