2013-04-11 77 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來查找並替換不想要的單詞並將該變量的內容重寫回文件中。