如何在文本文件android中删除行

时间:2013-01-12 05:13:59

标签: android

281〜名〜位置〜@时间@室温% 的 @ TIME2 @房间2 % @时间3 @ ROOM3; 我需要删除文本文件中的%后面的第二行。但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

BufferedReader in = null;
out = null;
File sdCard = Environment.getExternalStorageDirectory();
File root = new File (sdCard.getAbsolutePath() + "/yourFile");
try {
        InputStream instream = new FileInputStream(file);
        in = new BufferedReader(new InputStreamReader(instream));
        out = new PrintWriter(new File(root,"yournewFile));

        String line; //a line in the file

    while ((line = in.readLine()) != null) {
            if (!Pattern.matches("^some pattern.*",line)) { //find the line we want to delete
                      //if it is not the line you want to delete then write it to new file
                            out.println(line);
            }

    }

    in.close();
    out.flush();
        out.close();
        File oldFile = new File (root,"/yourFile");
        oldFile.delete();
        File newFile = new File (root,"/yournewFile");
        newFile.renameTo(oldFile);
}catch(Exception e) {
    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}

您应该读取旧文件并将其与要删除的行匹配。如果它不是您要删除的行,则将其写入另一个文件。这样您将获得只丢失了该行的新文件想要删除。 你完成了。它会有所帮助。