2017-06-05 84 views
0

我正在嘗試編寫該問題的程序:「編寫一個程序,該程序將向用戶提出一個字符串和一個文件名,然後從該字符串中刪除所有出現的字符串文本文件。」替換字符串刪除文本中的所有內容

這是我到目前爲止有:

import java.io.FileNotFoundException; 
    import java.io.PrintWriter; 
    import java.util.*; 

    public class RemoveText { 
     public static void main(String[] args){ 

    //creates a scanner to read the user's file name 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter a file name: "); 
    String fileName = input.nextLine(); 

    java.io.File file = new java.io.File(fileName); 
    java.io.File newFile = new java.io.File(fileName); 
    Scanner stringToRemove = new Scanner(System.in); 
    System.out.println("Enter a string you wish to remove: "); 
    String s1 = stringToRemove.nextLine(); 

    //creating input and output files 
    try { 
     Scanner inputFile = new Scanner(file); 
     //reads data from a file 
     while(inputFile.hasNext()) { 
      s1 += inputFile.nextLine(); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    //supposed to replace each instance of the user input string 
    //but instead deletes everything on the file and i don't know why 
    String s2 = s1.replaceAll(s1, ""); 

    try { 
     PrintWriter output = new PrintWriter(newFile); 
     output.write(s2); 
     output.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    //closing various scanners 
    input.close(); 
    stringToRemove.close(); 
    } 
} 

但由於某些原因,而不是用空格替換字符串,整個文本文件變空。我究竟做錯了什麼?

編輯:好的,我採納了大家的建議,並設法通過引入第三個字符串變量並使用更多描述性變量名來解決變量問題。

Scanner s1 = new Scanner(System.in); 
    String stringToRemove = s1.nextLine(); 
    String fileContents = null; 

    try { 
    //stuff here 
     while (inputFile.hasNextLine()) { 
     fileContents += inputFile.nextLine(); 
    } catch { //more stuff } 

    String outputContent = fileContents.replaceAll(stringToRemove, ""); 

我現在的問題是,新文件的開頭中繼新內容之前,「零」開始。

+2

因爲你保存文本和字符串刪除在同一個變量? (然後做:'s1.replaceAll(s1,「」)') – alfasin

+1

爲你的變量選擇好的名字。使用'stringToRemove'作爲第一個's1'(並且將當前的'stringToRemove'重命名爲'input'或類似的名稱),並且使用'fileContents'而不是's1'的第二次使用,將會奇蹟般地解釋爲什麼'fileContents .replaceAll(stringToRemove,「」)'是正確的,'stringToRemove.replaceAll(stringToRemove,「」)'返回一個空字符串 – tucuxi

回答

3
String s2 = s1.replaceAll(s1, ""); 

的replaceAll方法的第一個參數是你在找什麼來代替,而你正在尋找S1,你說這個代碼清理所有S1的內容...

1

你在哪裏錯了是您將文件內容附加到s1,這是您要刪除的字符串。 嘗試引入s3然後做

s2 = s3.replaceAll(s1,「」);

+1

順便說一句,將整個內容讀入內存是低效的。如果文件內容很長,您的程序將耗盡內存。 –

相關問題