从android上的文本文件中写入和读取特定行

时间:2014-07-20 15:26:39

标签: android java-io

我想从文件中读取特定的行,如text.txt,然后写一些字符串给它。在android上做任何方法吗?我还在玩LineNumberReader,但仍然无法找到方法。

感谢。

2 个答案:

答案 0 :(得分:0)

为什么不使用inputstream,bufferedreader,stringbuilder和outputstream的组合?

答案 1 :(得分:0)

也许有人会得到同样的情况......

private void Writing() {
    // TODO Auto-generated method stub
    try {
        String[] lines = new String[888];
        File internalStorage = Environment.getDataDirectory();
        File dir = new File (internalStorage + "/myPde");                   
        File file = new File(dir, "ekfslam.pde");
        File file_temp = new File(dir, "ekfslam_temp.txt");

        FileWriter fw = new FileWriter(file_temp,true);
        BufferedWriter bw = new BufferedWriter(fw);
        LineNumberReader lnr = new LineNumberReader(new FileReader(file));

        file_temp.createNewFile();

        int i = 0;
        String Line = "";
        while (true) {
            Line = lnr.readLine();
            if (Line != null) {
                lines[i]=Line;
                i++;
            } else {
                break;
            }
        }

        for (int j = 0; j < 50; j+=5) {
            lines[95] = lines[95]+"\n\t\t Data "+j;
        }           

        if (file_temp.exists()) {               
        } else {
            file_temp.createNewFile();
        }

        for (i = 0; i < lines.length; i++){
            bw.write(lines[i]);
            bw.newLine();
            System.out.println(lines[i]);
        }
        file.delete();
        file_temp.renameTo(file);
        bw.close();
        lnr.close();            
    } catch (Exception e) {
        e.printStackTrace();
    }

}