0

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

    }
}

3 Answers3

2

Do you mean like

System.out.println(list.get(i).replaceAll("SECRET", "******");
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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();
            }
        }
  }
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • And how would you remove an entire paragraph if the word "secret" is found. For ex: if you have 4 lines in a paragraph and the word secret is found, the entire paragrph should be removed. – Inside Here Jan 14 '13 at 10:19
  • @InsideHere paragraph or sentence? – Kevin Bowersox Jan 14 '13 at 10:20
  • paragraph that contains the word Secret. – Inside Here Jan 14 '13 at 10:22
  • You would need to store the text during each iteration of the StringReader into a StringBuilder. Once you encountered a blank line, you would then check the content of the StringBuilder and conditionally display. – Kevin Bowersox Jan 14 '13 at 10:25
0
if(line.indexOf("SECRET") > -1){
   System.out.println("Has Secret");
   continue;
}
Greg
  • 1,671
  • 2
  • 15
  • 30