2016-11-10 34 views
0

因此,我的代碼的目標是使用Scanner讀取文本文件,然後通過文本字段進行用戶輸入。如何使用掃描儀替換我的文本文件中的單詞?

然後,掃描器將遍歷文本文件,試圖找到所述用戶輸入的一個實例,如果該輸入被找到,它將替換文本文件中的單詞。

然後我回寫到文件,只改變了一個單詞。

我的問題是,我沒有使用過掃描儀之前,並通過文檔,我不確定如何正確進行。

這是到目前爲止我的代碼,在一個按鈕的點擊激活:

Scanner read = new Scanner("test test.txt"); 

    //Converting user input from editSerialField to a scanner 
    Scanner scEditSerial = new Scanner(editSerialField.getText()); 
    String scSerial = scEditSerial.nextLine(); 
    //Converting user input from editLocationField to a scanner 
    Scanner scEditLocation = new Scanner(editLocationField.getText()); 
    String scLocation = scEditSerial.nextLine(); 

    while (read.hasNextLine()) 
    { 
     //If my text file contains the user input from the text field 
     if (read.hasNext(scSerial)) 
     { 
      //Code to replace instance of editSerialField in text file 
     } 

     //Code to write back to the file 
    } 

如何使用Scanner到一個文本文件中的替換詞?我是否使用不同的班級來這樣做?

我堅持如何繼續我的代碼,所以任何幫助將不勝感激。

+0

所以*爲什麼*你想用'掃描儀'來讀取文件?你打算如何寫文件? 'FileWriter'周圍的'PrintWriter'?如果是這樣,爲什麼不在'FileReader'周圍使用'BufferedReader'? --- *僅供參考:*如果您所做的只是閱讀完整行,「BufferedReader」比'Scanner'快** **許多倍**,它真的是slooowwwwww *。 – Andreas

+0

我想讀取我的文件的所有行,並用另一個用戶輸入替換文本文件中的用戶輸入實例。我被告知使用'掃描儀'將是掃描線條並替換單詞的最佳方式。我不確定如何使用'Scanner'替換單詞。我是Java的新手,所以我不知道還有哪些類可以使用。 – juiceb0xk

+0

你不能*用'掃描儀'來代替單詞*。 'Scanner'用於*閱讀*(又名掃描)輸入。你可能對於正則表達式還不太熟悉,所以'indexOf()'和'substring()'可能是你用來替換字符串中文本的方法。 – Andreas

回答

0

你不能使用Scanner類。因爲Scanner類用於只讀。你可以按照以下代替的話:

Path path = Paths.get("test.txt"); 
Charset charset = StandardCharsets.UTF_8; 

String content = new String(Files.readAllBytes(path), charset); 
content = content.replaceAll("foo", "bar"); 
Files.write(path, content.getBytes(charset)); 

或者你也可以看到BufferedWriterFileWriter。你可以通過工作示例here