如何从android studio上的txt文件中获取单行

时间:2015-03-31 13:10:16

标签: java android

获取文件内容的我的代码:

private String readTxt(){

            InputStream inputStream = getResources().openRawResource(R.raw.text);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            int i;
            try {
                i = inputStream.read();
                while (i != -1)
                {
                   byteArrayOutputStream.write(i);
                   i = inputStream.read();
                }
                inputStream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return byteArrayOutputStream.toString();
        }

但我希望只提取该文件中的一个特定行。

1 个答案:

答案 0 :(得分:0)

使用BufferedReader代替ByteArrayOutputStream

String readLine(int line) throws IOException {

    InputStream in   = getResources().openRawResource(R.raw.text);
    BufferedReader r = new BufferedReader(new InputStreamReader(in));

    try {

        String lineStr  = null;
        int currentLine = 0;

        while ((lineStr = r.readLine()) != null) {

            if (currentLine++ == line) {
                return lineStr;
            }

        }
    } finally {
        if (r != null) {
            r.close();
        }
    }

    throw new IOException("line " + line + " not found");
}