Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: replaceAll() help

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post replaceAll() help

    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.
    Last edited by M0dSe7en; March 16th, 2012 at 05:34 PM.


  2. #2
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: replaceAll() help

    try to scan word by word.. and do a if statement to check if the word is and or random

    for example you could try:

    if (word.equals("and"))
    {
       --- CODE here (use Replace not ReplaceAll()..)
    }
    else if (word.equals("random"))
    {
    --- CODE here..
    }
    else{}

    This is only a quick demo to look over (use as reference and learn off it)
    Last edited by macko; March 17th, 2012 at 03:26 AM.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: replaceAll() help

    Your replace is for a substring no matter its context.
    Put the Strings into a context by adding delimiters before and after the String. For example spaces: " and ".
    There could be lots of different delimiters depending on what the source file contains. You might need a separate list for each type of source file you are scanning. And there could be different leading and following delimiters.

    i need to be able to overwrite the same file im using it on
    You should write to a new temp file. When the code completes successfully, delete the original (I'd rename it to be safe) and then rename to temp file to the name of the original.
    Overwriting the original is a bad idea. Especially during testing when there are bugs. Or what if the new file is different size than the old one?

Tags for this Thread