使用java/shell删除文件中字符串的最后一次出现 [英] Deleting the last occurence of a string in a file using java/shell

查看:173
本文介绍了使用java/shell删除文件中字符串的最后一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要删除字符串的最后一次出现,即文件中的VirtualHost.我可以用java,shell来做. 文件结构是一个xml文件.我需要的是将VirtualHost移至末尾.因此,我尝试将其删除然后追加.

need to delete the last occurence of a string i.e. VirtualHost in a file. I can do it using java, shell. The file structure is an xml file. What I need is I need to shift the VirtualHost to the end. So I am trying to remove it and then append.

 Current Text:
    </VirtualHost>
    #Added for Patch 
    <LocationMatch ^/bea_wls_internal/>
    RewriteOptions inherit
    </LocationMatch>







Desired Text:
#Added for Patch
<LocationMatch ^/bea_wls_internal/>
RewriteOptions inherit
</LocationMatch>
</VirtualHost> 

我试图这样做:

    int c=1,i=1;
    int loc[]=new int[10];
    //String str="</VirtualHost>";
    BufferedReader br= new BufferedReader (new FileReader ());
    String line=br.readLine();
    FileWriter fw=new FileWriter(file_location);
    PrintWriter pw=new PrintWriter(fw);
    List<String> lines = new ArrayList<String>();

    while ((line != null)){
            //System.out.println(line);
            lines.add(line);
            c++;
            line=br.readLine();
    }
    br.close();
    int size=lines.size();
    System.out.println("size "+size);

    while(c>i){
        int filesize=lines.size();
        System.out.println(filesize);

        String str=lines.get(filesize-i);
        System.out.println(str);
        lines.remove(filesize-i);
        if (!lines.equals("</VirtualHost>")){
            System.out.println("inside if");
            lines.add(str);
            //break;
        }
        else if(lines.equals("</VirtualHost>")){
            break;
        }
        i++;
    }
    for (String writeLine : lines)
            pw.println(writeLine);


    pw.append("</VirtualHost>");
    pw.flush();
    pw.close();
    fw.close();
    System.out.println(c);
}

}

推荐答案

使用可以提供java对象的XML解析器.然后从根目录遍历到所需元素,即可执行所有操作

Use XML parser which can provide the java object. Then traverse from root to desired element and you can perform all manipulation

这篇关于使用java/shell删除文件中字符串的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆