2015-07-02 153 views
1

我想製作一個從文件中刪除文本的程序。要刪除的文本和文件路徑是作爲命令行參數提供的。一切都很順利,但是當程序運行完畢後打開文件時,它全部是空的。我究竟做錯了什麼?文件輸出刪除所有內容

import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Scanner; 

public class Remove { 
public static void main(String[] args) throws IOException{ 
    if(args.length != 2) { 
     System.out.println("usage : java Remove stringToRemove filePath"); 
     System.exit(1); 
    } 
    String stringToReplace = args[0]; 
    String path = args[1]; 
    File file = new File(path); 
    if(!file.exists()) { 
     System.out.println("No such file exists!"); 
     System.exit(2); 
    } 

    Scanner input = new Scanner(file); 
    PrintWriter output = new PrintWriter(file); 

    while(input.hasNext()) { 
     String currentLine = input.nextLine(); 
     currentLine = currentLine.replaceAll(stringToReplace, ""); 
     output.println(currentLine); 
    } 

    input.close(); 
    output.close(); 

    System.out.println("Operation Successful"); 
} 
} 
+0

阿漢!謝謝... – Saud

+0

是............ – Saud

回答

1

打開用於寫入的文件清除文件,所以如果輸入和輸出文件是相同的,那麼輸入將被清除,會發生什麼,因爲沒有線。