简体   繁体   English

审查输入文本文件并将其写入输出文本文件

[英]Censoring an input text file and writing it to an output text file

I'm writing a program that inputs a list of words and a list of banned words. 我正在编写一个输入单词列表和禁止单词列表的程序。 It will then "censor" the original list of words by changing any banned word in that file to asterisks. 然后,它将文件中所有禁止的单词更改为星号,从而“审查”单词的原始列表。 Finally, it will write the censored list of words into an output file. 最后,它将把经过审查的单词列表写入输出文件。 This is what I have so far 这就是我到目前为止

import java.util.*;
import java.io.*;

public class Assignment_5 {
public static void main(String[] args) {
   try{
  ArrayList<String> bWords = new ArrayList<String>();
  ArrayList<String> words = new ArrayList<String>();
  Scanner sc = new Scanner(new FileInputStream ("banned.txt"));
  PrintWriter pw = new PrintWriter ("output.txt");
  while(sc.hasNext()){
    bWords.add(sc.next());
  }
  sc = new Scanner(new FileInputStream("input.txt"));
  while (sc.hasNext())
    words.add(sc.next());

  String replacement = "test";
  for (int i = 0; i < words.size(); i++){
    for (int j = 0; j < bWords.size(); j++){
      if (words.get(i).compareTo(bWords.get(j)) == 0){
        for (int k = 0; k < words.get(i).length(); k++)
          replacement = "*";
        words.set(i, replacement);
        replacement = ""; 
      } 
    }

    for(i=0; i< words.size(); i++){
         pw.println(words.get(i));
        }
        pw.close();
     }
   }
   catch(Exception e){
     System.out.println(e.toString());
   }

It compiles fine and it creates an "output.txt" file, but the file is blank. 它可以正常编译并创建一个“ output.txt”文件,但该文件为空白。 I can't seem to figure out why it won't work. 我似乎无法弄清楚为什么它不起作用。 Any help would be great 任何帮助都会很棒

UDPATE: It now prints out because I added a for loop in front of the PrintWriter (updated in code), but now it's only printing out the input, and not the censored input UDPATE:现在打印出来,因为我在PrintWriter前面添加了一个for循环(在代码中更新了),但是现在它仅打印出输入,而不是检查输入

PrintWriter pw = new PrintWriter ("output.txt");

this line in code is rewriting the file again and again. 此行代码一次又一次地重写文件。 what you can do is put this out of loop. 您可以做的就是将其置于循环之外。 Also don't forget to close the stream after end of loop. 同样不要忘记在循环结束后关闭流。

pw.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM