Search code examples
javaandroidline

How to check if a line from txt file startswith "h" in android?


I'm developing a Livestream app which supports a MaterialFileChooser, but I'm struggling to check if a line from the chosen text file starts with "h" the lines (that start with h) should be stored in a string.

I tried this:

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

Solution

  • I do not understand what do you mean by "should be stored in a string". If you need the line that starts with "h" just create an ArrayList of strings and save it there.

    // Declare an ArrayList first 
    private ArrayList<String> lineStore = new ArrayList<String>();
    
    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")) {
                       // Store the line in the ArrayList to be used later
                       lineStore.add(line); // That's what you meant? 
                   }
                }
    
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }