如何通过filereader从txt文件中读取并写入修改后的



我必须通过filereader读取一个txt文件,并通过删除所有以"c";以及";C";并通过创建一个经过审查的新txt文件来编写它。我已经完成了以下操作,但我需要使用Stream((在一个方法中进行读写。我做过类似的smtg,但它必须使用流,而不是通过创建不同的列表和char数组等。


我做过类似的smtg,但它必须使用流,而不是通过创建不同的列表和char数组等。

public class Censored {
static String words = "";
static String censoredWords = "";
static List<String> myWords = new ArrayList<>();
public static void main(String[] args) {    
System.out.println(censorTxt());
convertListToStringAndChar();
}
private static List<String> censorTxt() {
try (
FileReader in = new FileReader("resources/input.txt");
){          
int read = 0;
while (read != -1) {
read = in.read();
String myChar = Character.toString((char) read);                 
String word = myChar;
words = words + word;
}
String[] splitedTextArray = words.split(" ");
for (String elements : splitedTextArray) {
if (!elements.startsWith("c")) {                    
myWords.add(elements);
}
}
return myWords;
} catch (IOException e) {
System.out.println("smtg went wrong");
}
return null;
}
private static void convertListToStringAndChar() {
try {
FileWriter out = new FileWriter("resources/censored_content.txt");
for (String strings : myWords) {

censoredWords += strings;
}
for (int i = 0 ; i < censoredWords.length() ; i++) {
int c = censoredWords.charAt(i);                
out.write(c);                   
}               
out.close();
} catch (IOException e) {
e.printStackTrace();
}       
}
}

使用Files.lines()在输入文件中提供字符串流的可能实现。

这里没有创建中间列表,经过审查的单词被写入特定的文本文件。

public static void readAndFilter(String inputFile, String outputFile) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile), StandardOpenOption.CREATE);
Stream<String> input = Files.lines(Paths.get(inputFile))) {
input
.flatMap(line -> Arrays.stream(line.split("\s+")))
.filter(word -> !word.isEmpty())
.filter(word -> 'c' == Character.toLowerCase(word.charAt(0)))
.forEach(censored -> {
try {
writer.write(censored);
writer.newLine();
} catch (IOException ioex) {
System.err.println(ioex);
}
});
}
}
public static void main(String[] args) throws IOException {
readAndFilter("my_input.txt", "censored.txt");
}

最新更新