Search code examples
javaiobufferedreadername-hiding

Java i/o reading a text while hiding specific words


How would you read the following text while hiding the word SECRET each times it appears ? here is the text :

this line has a secret word.

this line does not have a one.

this line has two secret words.

this line does not have any.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class BufferedReadertest {

    public static void main(String[] args) {

        ArrayList <String>list = new ArrayList<>();


        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("secretwords.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                list.add(sCurrentLine);

                }

            for (int i = 0; i < list.size(); i++) {

                System.out.println(list.get(i));
            }



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

Solution

  • I'm n seeing the need to use an ArrayList. Replace SECRET and print the message when iterating the buffered reader.

    public static void main(String[] args) {
    
            BufferedReader br = null;
    
            try {
    
                String sCurrentLine;
    
                br = new BufferedReader(new FileReader("secretwords.txt"));
    
                while ((sCurrentLine = br.readLine()) != null) {
                    System.out.println(sCurrentLine.replaceAll("SECRET", ""));
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
      }