请考虑以下代码。我不熟悉StringBuilders或读/写数据。我需要:
1。)开源文件
2。)抓住单词并检查旧字符串,如果是旧字符串,则添加新字符串
3.。)使用PrintWriter并关闭。我正在修改以下代码:
import java.io.*;
import java.util.*;
public class ReplaceText {
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 4) {
System.out.println(
"Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(1);
}
// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
input.close();
output.close();
}
}
我还想在运行时向用户询问源文件,旧字符串和新字符串,而不是使用命令行参数。
我知道我仍然需要整合StringBuilder。以下是我到目前为止的情况:
public class ReplaceText {
public static void main(String [] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("What is the source file");
java.io.File file = new java.io.File(scan.next());
System.out.println("Enter old line");
String oldLine = scan.nextLine();
System.out.println("Enter new line");
String newLine = scan.nextLine();
//scan.exit;
/** Read one line at a time, append, replace oldLine with
* newLine using a loop */
//Scanner scan2 = new Scanner(file);
//PrintWriter that replaces file
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(file);
output.close();
}
}