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");
}
}
阿漢!謝謝... – Saud
是............ – Saud