Question

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

    }
}
Était-ce utile?

La solution 2

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

Autres conseils

Do you mean like

System.out.println(list.get(i).replaceAll("SECRET", "******");
if(line.indexOf("SECRET") > -1){
   System.out.println("Has Secret");
   continue;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top