下面的代码应该读取文件MainFile.txt中的每一行,检查每行是否包含来自Set的标记。如果确实包含,请将其替换为“xxx”字符串。然后使用BufferedWriter编写一个新文件。 输出ConvFile.txt与输入完全相同。
MainFile.txt:
car, 18, train, 19, bus,
laptop, 20, tablet, 21, computer,
swim, 22, bike, 23, run,
public class ReplaceWords {
Set<String> wordToReplace;
public ReplaceWords(){
this.wordToReplace = new HashSet<>();
this.wordToReplace.add("18");
this.wordToReplace.add("19");
this.wordToReplace.add("20");
this.wordToReplace.add("21");
this.wordToReplace.add("22");
this.wordToReplace.add("23");
}
public void redactFile(){
String inPathname = "E:\\SkyDrive\\Java\\Coding\\FileChgOne\\MainFile.txt";
String outPathname = "E:\\SkyDrive\\Java\\Coding\\FileChgOne\\ConvFile.txt";
File inFile = new File(inPathname);
File outFile = new File(outPathname);
Scanner bufferedScanner = null;
BufferedWriter bufferedFileWriter = null;
try {
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(inFile)));
bufferedFileWriter = new BufferedWriter(new FileWriter(outFile));
while(bufferedScanner.hasNextLine()){
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
while(lineScanner.hasNext()){
String currentToken = lineScanner.next();
if (this.wordToReplace.contains(currentToken)){
bufferedFileWriter.write("xxx, ");
}
else {
bufferedFileWriter.write(currentToken + ", ");
}
}
bufferedFileWriter.newLine();
}
}
catch (Exception en){
System.out.println("error: " + en);
}
finally {
try {
bufferedScanner.close();
bufferedFileWriter.close();
}
catch (Exception en) {
System.out.println(en);
}
}
}
}
输出ConvFile.txt:
car, 18, train, 19, bus,
laptop, 20, tablet, 21, computer,
swim, 22, bike, 23, run,
答案 0 :(得分:1)
令牌需要修剪,即当扫描仪读取令牌时应删除逗号后的空格:
while(lineScanner.hasNext()){
String currentToken = lineScanner.next();
currentToken = currentToken.trim(); // line to add
if (this.wordToReplace.contains(currentToken)){
bufferedFileWriter.write("xxx, ");
}
else {
bufferedFileWriter.write(currentToken + ", ");
}
}
您也可以通过在评论中更新Marko Topolnik建议的Scanner
分隔符模式来完成此操作。
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter("\\s*,\\s*");
\\s*
表示零个或多个空白字符。