import java.io.*;
import java.util.*;
public class replace {
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 4) { // obviously, once i remove the "newStr" arg (arg[4]) this will become args.length != 3
System.out.println(
"Usage: java replace sourceFile targetFile oldStr newStr"); //that's how i call it - need to remove "newStr" arg
System.exit(0);
}
// 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(0);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists"); // this is what i want to change to overwrite to same file
System.exit(0);
}
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
while (input.hasNext()) {
/*
if (input.hasNext("math.random()")){
input.skip("math.random()");
System.out.println("skipped math.random()");
}if(input.hasNext("math.Rand()")){
input.skip("math.Rand()");
System.out.println("skipped math.Rand()");
}
*/
// above ^^ is what i tried to skip certain patterns of text, but when i tested i had no changed output
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]); // i understand why it doesn't work when i try to replace text to programming specific characters like replacing 'and' to '&&' but is there a way to make it work?
output.println(s2);
}
input.close();
output.close();
}
}