如何在android中检查txt文件中的一行是否以“h”开头?

我正在开发一个支持 MaterialFileChooser 的 Livestream 应用程序,但我正在努力检查所选文本文件中的一行是否以“h”开头,这些行(以 h 开头)应该存储在一个字符串中。


我试过这个:


protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1000 && resultCode == RESULT_OK) {

        String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);


        try {

            BufferedReader br = new BufferedReader(new FileReader(filePath));

            String line;

            while ((line = br.readLine()) != null) {

               if (line.startsWith("h")) {

                   // Confusion

               }

            }


            br.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


PIPIONE
浏览 68回答 1
1回答

慕无忌1623718

我不明白“应该存储在字符串中”是什么意思。如果您需要以“h”开头的行,只需创建一个ArrayList字符串并将其保存在那里。// Declare an ArrayList first&nbsp;private ArrayList<String> lineStore = new ArrayList<String>();protected void onActivityResult(int requestCode, int resultCode, Intent data) {&nbsp; &nbsp; if (requestCode == 1000 && resultCode == RESULT_OK) {&nbsp; &nbsp; &nbsp; &nbsp; String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BufferedReader br = new BufferedReader(new FileReader(filePath));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String line;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((line = br.readLine()) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (line.startsWith("h")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Store the line in the ArrayList to be used later&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lineStore.add(line); // That's what you meant?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; br.close();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java