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();
}
}
你好,我在过滤部分遇到了一个问题。基本上,我的代码要求用户输入一个命令,例如:过滤(路径在此)(要从文本文件中删除的单词)
一切都很好,但过滤器的部分,我被要求流媒体文件,然后覆盖过滤后的版本。我被要求对文件进行流式处理,然后覆盖过滤后的版本。我已经测试过了,流媒体和重写工作都很好,我只是在实际的过滤过程中出现了问题,希望你能帮助我:) 问题出在流媒体文件后的DoTheFilter方法中。
所有的内容都在 DoTheFilter
方法可以合并为一个 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();
}
注意到以下几点。
Stream
您将面临NPE的风险 line.collect(Collectors.toList());
. 这应该在try块中处理,只要你想避免使用 null
.newtext.stream().filter(str -> word.contains(str));
不做任何事情,因为流没有用终端操作关闭,如 forEach
, collect
, reduce
等。中间的操作将不会生效。IOException
而非泛泛 Exception
.