删除以字符串开头的txt文件中的所有行? (JAVA)

时间:2014-12-05 17:55:42

标签: java

是的,所以我说这个文件格式为:


MYFILE.TXT

名称昵称;

jay epic1;

jay epic2;


现在说我有String name = jay;。我想删除所有以字符串name

开头的行


基本上,我想删除以字符串开头的txt文件中的所有行。可能?如果是这样,有人可以给我代码吗? (通过查看代码本身,我学得最好。)


感谢,

1 个答案:

答案 0 :(得分:1)

以下是一种可能的实施方式:

    String name = "jay ";

    String source = "/path/to/original/file.txt";
    String dest = "/path/to/new/modified/file.txt";

    File fin = new File( source );
    FileInputStream fis = new FileInputStream( fin );
    BufferedReader in = new BufferedReader( new InputStreamReader( fis ) );

    FileWriter fstream = new FileWriter( dest, true );
    BufferedWriter out = new BufferedWriter( fstream );

    String aLine = null;
    while( ( aLine = in.readLine() ) != null ) {
        // Check each line for the string, and write if it doesn't have it:
        if( !aLine.startsWith(name) ) {
            out.write( aLine );
            out.newLine();
        }
    }

    in.close();
    out.close();