0

281~名字~位置~@time@room% @time2@ room2%@time3@room3; 我需要删除文本文件中 % 之后的第二行。但我不知道该怎么做。

4

1 回答 1

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();
}

您应该阅读旧文件并将其与要删除的行匹配。如果它不是您要删除的行,则将其写入另一个文件。因此,您将获得仅缺少要删除的行的新文件. 你完成了。希望它会有所帮助。

于 2013-01-12T05:50:37.330 回答