'With a scanner search on ArrayList the content and print the line

I have a text file (.txt) and I'm stuck here. I user a BufferReader to read all file and save in a ArrayList then put the ArrayList into a String to remove the , [ ] Now I need to find the word of the scanner ex: (1001) in the ArrayList that the user want, and print the line of this word and the 4 lines after that. After that, edit this 4 lines and save the ArrayList to a file.

Or have something more simple without using ArrayLists? Thank you.

System.out.println("Digite o ID ou 1 para sair: ");
                Scanner sOPFicheiro = new Scanner(System.in);
                opFicheiro = sOPFicheiro.nextInt();
                     if (opFicheiro == 1){
                         System.out.println("A voltar ao menu anterior...");
                         Thread.sleep(1000);
                         editarFicheiro();
                     } else {
                            //Envia para um ArrayList o ficheiro Formandos
                            ArrayList<String> textoFormandos = new ArrayList<String>();
                            BufferedReader ler = new BufferedReader(new FileReader(FichFormandos));
                            String linha;
                        while ((linha = ler.readLine()) != null) {
                            textoFormandos.add(linha + "\n");
                        }
                        ler.close();
                              
                              //Remove , [ ] do ArrayList para enviar para o ficheiro
                              String textoFormandos2 = Arrays.toString(textoFormandos.toArray()).replace("[", "").replace("]", "").replace(",", "");
                         
                     }

File: Txt File



Solution 1:[1]

Instead of using an ArrayList use a StringBuilder :

    StringBuilder textoFormandos = new StringBuilder();
    while ...
        textoFormandos.append(linha + "\n");
    ...
    String textoFormandos2 = textoFormandos.toString();

This way you won't need to remove anything. For the rest you need to clear the requirements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nenito