如何删除文本文件的Andr​​oid线 [英] How to delete line in textfile android

查看:159
本文介绍了如何删除文本文件的Andr​​oid线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


解决方案

 中的BufferedReader = NULL;
出= NULL;
文件SD卡= Environment.getExternalStorageDirectory();
文件根=新的文件(sdCard.getAbsolutePath()+/ yourFile);
尝试{
        InputStream的河道=新的FileInputStream(文件);
        在=新的BufferedReader(新的InputStreamReader(河道));
        OUT =的新PrintWriter(新文件(根,yournewFile));        串线; //在文件中的线    而((行= in.readLine())!= NULL){
            如果(!Pattern.matches(^一些模式。*,行)){//找到我们想要删除的行
                      //如果不是你要删除的行,然后把它写入新文件
                            通过out.println(线);
            }    }    附寄();
    了out.flush();
        out.close();
        文件的oldfile =新的文件(根/ yourFile);
        oldFile.delete();
        文件NEWFILE =新的文件(根/ yournewFile);
        newFile.renameTo(oldfile目录);
}赶上(例外五){
    Toast.makeText(getApplicationContext(),e.​​toString(),Toast.LENGTH_SHORT).show();
}

您应该阅读旧文件,并将其匹配到要delete.if这行是不是要删除,然后将其写入到另一个file.thus你会得到新的文件,只有该行缺行,你要删除。
你done.hope它将帮助。

281~name~location~@time@room% @time2@room2% @time3@room3; I need to delete the second line after the % in text file. But i dont know how to do that.

解决方案

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

You should read old file and match it to the line you want to delete.if it is not the line you want to delete then write it to another file.thus you will get the new file with only that line missing which you wanted to delete. you are done.hope it will help.

这篇关于如何删除文本文件的Andr​​oid线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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