文件输出删除所有内容
File output deletes all the content
我正在尝试制作一个从文件中删除文本的程序。要删除的文本和文件路径作为命令行参数提供。一切顺利,但是当我在程序完成 运行 后打开文件时,它是空的。我做错了什么?
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");
}
}
打开文件进行写入会清除文件,因此如果输入和输出文件相同,则输入将被清除并且不会发生任何事情,因为没有行。
我正在尝试制作一个从文件中删除文本的程序。要删除的文本和文件路径作为命令行参数提供。一切顺利,但是当我在程序完成 运行 后打开文件时,它是空的。我做错了什么?
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");
}
}
打开文件进行写入会清除文件,因此如果输入和输出文件相同,则输入将被清除并且不会发生任何事情,因为没有行。