TheAfterLife
TheAfterLife

Reputation: 11

removing words inputted by the user using stream and filter in java

public class FilterText {
    Path path;
    String p;
    List<String> word=new ArrayList<String>();
    public FilterText(String[] words) {
        this.path=Paths.get(words[1]);
        p=words[1];
        this.word.addAll(Arrays.asList(words));
        word.remove(0);
        word.remove(0);
    }

    public void DoTheFilter() {
        Stream<String> line = null;
        try {
            line = Files.lines(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
         List<String> newtext=line.collect(Collectors.toList());
         newtext.stream().filter(str -> word.contains(str));

          try {

                 File f=new File(p);
                 FileWriter fw=new FileWriter(f,false);
                 for ( String s : newtext) {
                 fw.write(s);
                 fw.write(System.lineSeparator());
                 }
                 fw.close();
             } catch (Exception e) {
                 e.printStackTrace();
             }
    }

Hello, I'm facing a problem with the filtering part. Basically my code asks input from the user to input a command, for example : Filter (path here) (words to remove from the text file)

Everything is working fine but the filter part. I'm asked to stream the file and then overwrite the filtered version. Streaming and rewriting is working fine as I've tested it, I only have a problem with the actual filtering, hope you can help :) The problem is located in the method DoTheFilter, after streaming the file.

Upvotes: 0

Views: 686

Answers (1)

Nikolas
Nikolas

Reputation: 44398

All the content inside the DoTheFilter method can be merged into one try-catch:

try {
    List<String> newtext = Files.lines(path)
        .filter(str -> word.contains(str))
        .collect(Collectors.toList());

    File f = new File(p);
    FileWriter fw = new FileWriter(f, false);
    for (String s: newtext) {
        fw.write(s);
        fw.write(System.lineSeparator());
    }
    fw.close();
} catch (IOExceptione) {
    e.printStackTrace();
}

Note the following:

  • With separation of Stream you risk NPE on the line.collect(Collectors.toList());. This should be handled in the try block as long as you want to avoid programming with null.
  • newtext.stream().filter(str -> word.contains(str)); doesn't do anything since the stream is not closed with a terminal operation, such as forEach, collect, reduce etc. The intermediate operations will not take effect.
  • Catch IOException rather than more general Exception.

Upvotes: 1

Related Questions