Firstly, I haven't made this code because I've never dealt with reading text from another file, so beside using scanners the PrintWriter and ReplaceAll() were new to me.
So basically what i'm trying to build is a code optimizer that i can build a .bat file around to quickly optimize some of code for other programming languages.
So far i have 3 problems.
1. I can't figure out how skip certain patterns (for example in one file im testing with it has a Random() when i set this program to replaceAll("and","and1") it not only changed the and's to and1's but random() to rand1m()).
2. It can't accept programming symbols in certain syntax, i need to be able to replace text with any character i need (ex. change all "and" to "&&"), when i try to do this i get syntax error in cmd.
3. i need to be able to overwrite the same file im using it on (so if i used a.txt i want all the revisions done on a.txt not have an output file ex. b.txt). Thanks guys
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(); } }
this code is pretty vanilla i just added the commented part. I've only been coding java for about a year (i'm 16) but i could really use the help guys, i can really learn from this too later on i may need to store text in another file and call it to a program. thanks for the help.