2013-04-11 119 views
0

我目前正在尝试编写一个程序,该程序可以扫描文本文档并用另一个短语替换指定的单词/字符串/任何内容,具体使用类Scanner和PrintWriter的。不幸的是,我在查找正确的方法以及如何实现它们方面遇到了一些麻烦。这里是我的代码:使用Scanner和Printwriter类查找和替换文本文件中的单词

class Redaction { 

    public static void main(String[] args) throws FileNotFoundException { 
     Scanner input = new Scanner(System.in); 

     System.out 
       .println("Please enter the filename of the sensitive  information"); 
     String f = input.next(); 
     System.out.println("Please input what text you want 'lost'"); 
     String o = input.next(); 
     System.out 
       .println("Please input what you want the new, improved filename to be called"); 
     String n = input.next(); 

     File sensitiveDocument = new File(f); 
     if (!sensitiveDocument.exists()) { 

      System.out.println("File does not exist."); 

      System.exit(0); 

     } 

     Scanner in = new Scanner(sensitiveDocument); 
     in.useDelimiter("[^A-Za-z]+"); 
     PrintWriter out = new PrintWriter(n); 

     while (in.hasNext()) { 
      if (in.hasNext(o)) { 
       // ... 
      } 
     } 

     in.close(); 
     out.close(); 
    } 
} 

我几乎失去了在这一点上。任何帮助将非常感激。

+0

但是如果'(in.hasNext(o))'里面没有代码。你对什么感到困惑? – 2013-04-11 06:23:22

+0

看看我的答案在这里:希望它会帮助! http://stackoverflow.com/questions/7779265/find-and-replace-a-word-in-several-text-files-with-java/19246348#19246348 Nikhil 2013-10-08 11:33:09

回答

0

首先阅读PrintWriterScanner文档,决定使用哪些方法。

Pseodo代码:

  1. 获取逐行(或一字一句,取决于你想要删除的内容)。
  2. 寻找要删除的字符串
  3. 如果字符串中包含要删除的内容,请将其删除。
  4. 将字符串打印到文件中。
0

最简单的,虽然效率不高的算法是将文件内容读入字符串变量。之后,您可以使用String Tokenizer来查找并替换不想要的单词并将该变量的内容重写回文件中。

相关问题