目录
1、使用编译器调用
2、使用Command line调用
3、运行示例
1、使用编译器调用
import java.util.Scanner;
public class DeleteTxt {
public static void main(String[] args) throws IOException {
File sourceFile = new File("John.txt");
File targetFile = new File("John1.txt");
try (Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile))
{
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replace("John", " ");
output.println(s2);
}
}
}
}
2、使用Command line调用
1)改args.length!=3 2)原args[3]替换为空字符串
// command line java ReplaceText.java John.txt NewJohn1.txt John
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReplaceText {
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Usage:java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(1);
}
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file" + args[0] + "does not exist");
System.exit(2);
}
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
try (
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile)) {
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], "");
output.println(s2);
}
}
}
}
3、运行示例
John.txt-记事本
John is a good man.
John is a good man.
NewJohn.txt-记事本
is a good man.
is a good man.



