Results 1 to 10 of 10
  1. #1
    Join Date
    Jan 2009
    Posts
    90
    Rep Power
    0

    Default replace a string using Text i/o

    This program is to replace all the occurrences of a specific string from a text file.
    let say to remove John from a text file.

    on i/o this topic i just started learning it and im not really sure what are my logical errors. So can somebody please give me some advice on this program. Thanks!


    in command prompt i passed in
    java removeText.java John john.txt

    Java Code:
    import java.io.*;
    import java.util.*;
    
    	public class removeText
    	{
    		public static void main (String[] args) throws Exception
    		{
    			// Check command line parameter usage
    			if(args.length !=2)
    			{
    				System.out.println("Usage: java Exercise8.21 John FileName");
    				  System.exit(0);
    			}
    
    			//Check FileName if exists
    			File SourceFile = new File(args[1]);
    			if(!SourceFile.exists())
    			{
    				System.out.println("Source file "+args[1]+" does not exist");
    				System.exit(0);
    			}
    
    			//Create input and output files
    			Scanner input= new Scanner(SourceFile);
    			PrintWriter output = new PrintWriter(SourceFile);
    
    			while(input.hasNext())
    			{
    				String s1 = input.nextLine();
    				String s2 = s1.replaceAll(args[0], "");
                                                       	output.println(s2);
    			}
    			 input.close();
    			 output.close();
    		}//end of main
    	}//end of removeText
    Last edited by PureAwesomeness; 07-05-2009 at 02:38 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You can't input and output to the same source file. Instead how about writing to a dummy file, then after complete, rename it to the source file's name, thereby overwriting the source file.

  3. #3
    Join Date
    Jan 2009
    Posts
    90
    Rep Power
    0

    Default

    the question that i have requires me to pass in only one file.

    if possible can you give me an example of using a dummy file?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You only need to pass in a single file parameter. Simply create a new file with a name of your choosing, and then write to it. If you don't know how to do this, then have a peek at the IO tutorial on the Sun tutorial site, and you'll be able to learn all you need to know.

  5. #5
    Join Date
    Jan 2009
    Posts
    90
    Rep Power
    0

    Default

    can I create a dummy file(a copy of sourceFile) and then use one of them as scanner and the other one as printwriter?

  6. #6
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    @ Fubarable it is possible to read/write to the same file, as long as all reading is complete before the OutputStream to the file is opened...

    so some psuedocode for you... (I'm avoiding the dummy file idea, which may be better)
    Java Code:
    test file validity and create Scanner.
    Read all the lines in the file and store them in an array/ArrayList //probably ArrayList...
    Create PrintWriter.
    for(all lines in array/ArrayList){
    Remove String that needs to be removed
    Write line to file
    }
    Close Scanner and PrintWriter
    Of course some of this could be moved around, but it's the general idea.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Singing Boyo View Post
    @ Fubarable it is possible to read/write to the same file, as long as all reading is complete before the OutputStream to the file is opened...
    Yep, thanks for the clarification, ... but this will fall flat if the files are large. Streaming in place with a dummy file doesn't have this limitation and at least in my opinion is a better idea.

  8. #8
    Join Date
    Jan 2009
    Posts
    90
    Rep Power
    0

    Default

    This is Singing Boyo's suggestion but the codes have errors
    Java Code:
    import java.io.*;
    import java.util.*;
    
    	public class test
    	{
    		public static void main (String[] args) throws Exception
    		{
    			// Check command line parameter usage
    			if(args.length !=2)
    			{
    				System.out.println("Usage: java test John FileName");
          			System.exit(0);
    			}
    
    			//Check FileName if exists
    			File SourceFile = new File(args[1]);
    			if(!SourceFile.exists())
    			{
    				System.out.println("Source file "+args[1]+" does not exist");
    				System.exit(0);
    			}
    
    			//Create input and output files
    			Scanner input= new Scanner(SourceFile);
    
    			char[] chars;
    			while(input.hasNext())
    			{
    				String s1 = input.nextLine();
    			    chars = s1.toCharArray(s1.split(" "));
    			}
    
    			for(int i=0; i<chars.length; i++)
    			{
    				if(chars[i] == "John")
    				chars[i].replaceAll(chars[i],"");
    			}
    			PrintWriter output = new PrintWriter(SourceFile);
    
    			for(int i=0; i<chars.length; i++)
    			{
    				output.print(chars[i]+ " ");
    			}
    			 input.close();
    			 output.close();
    		}//end of main
    	}//end of exercise8.21
    This is Fubarable suggestion of creating a dummy file but it also has some errors in it

    Java Code:
    import java.io.*;
    import java.util.*;
    
    	public class test
    	{
    		public static void main (String[] args) throws Exception
    		{
    			// Check command line parameter usage
    			if(args.length !=2)
    			{
    				System.out.println("Usage: java test John FileName");
          			System.exit(0);
    			}
    
    			//Check FileName if exists
    			File SourceFile = new File(args[1]);
    			if(!SourceFile.exists())
    			{
    				System.out.println("Source file "+args[1]+" does not exist");
    				System.exit(0);
    			}
    
    			//char[] char = SourceFile.toCharArray()
    
    			//Create a dummy file
    
    			File DummyFile = new File("TempFile.txt");
    			boolean renameFile = DummyFile.renameTo(SourceFile);
    
    			//Create a target file
    
    			File TargetFile = new File(args[1]);
    
    
    			//Create input and output files
    			Scanner input= new Scanner(DummyFile);
    			PrintWriter output = new PrintWriter(TargetFile);
    
    			while(input.hasNext())
    			{
    				String s1 = input.next();
    				String s2 = s1.replaceAll(args[0], "");
    				output.println(s2);
    
    			}
    			DummyFile.delete();
    			 input.close();
    			 output.close();
    		}//end of main
    	}//end of test
    can someone please help me with some of those errors?
    Last edited by PureAwesomeness; 07-06-2009 at 01:38 AM.

  9. #9
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    Java Code:
    			while(input.hasNext())
    			{
    				String s1 = input.nextLine();
          [B]  // WHAT? what are you trying to do?
    			    chars = s1.toCharArray(s1.split(" "));[/B]
    			}
    
    			for(int i=0; i<chars.length; i++)
    			{
       [B]     // err... no you can't compare a char to a string.
    				if(chars[i] == "John")
            // no such method for chars
    				chars[i].replaceAll(chars[i],"");
    [/B]			}
    I'd suggest that you read a file, then write to a dummy file to see if they are exactly the same before you try to edit the text. This way, you know there's no coding error in reading/writing.

    btw, there is a third option which was not suggested for good reasons.
    Java Code:
    [COLOR=NAVY]import[/COLOR] java[COLOR=BLACK].[/COLOR]io[COLOR=BLACK].[/COLOR][COLOR=BLACK]*[/COLOR][COLOR=BLACK];[/COLOR]
    [COLOR=PURPLE]public[/COLOR] [COLOR=PURPLE]class[/COLOR] RandomAccessFileDemo [COLOR=BLACK]{[/COLOR]
      [COLOR=PURPLE]public[/COLOR] [COLOR=PURPLE]static[/COLOR] [COLOR=PURPLE]final[/COLOR] String NEWLINE [COLOR=BLACK]=[/COLOR] 
        System[COLOR=BLACK].[/COLOR]getProperty[COLOR=BLACK]([/COLOR][COLOR=SILVER]"line.separator"[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
      
      [COLOR=PURPLE]public[/COLOR] [COLOR=PURPLE]static[/COLOR] [COLOR=PURPLE]void[/COLOR] main[COLOR=BLACK]([/COLOR]String[COLOR=BLACK][[/COLOR][COLOR=BLACK]][/COLOR] args[COLOR=BLACK])[/COLOR][COLOR=BLACK]{[/COLOR]
        [COLOR=NAVY]try[/COLOR][COLOR=BLACK]{[/COLOR]
          RandomAccessFile raf [COLOR=BLACK]=[/COLOR] [COLOR=NAVY]new[/COLOR] RandomAccessFile
              [COLOR=BLACK]([/COLOR][COLOR=SILVER]"hey.txt"[/COLOR][COLOR=GREEN]/*file-name*/[/COLOR][COLOR=BLACK],[/COLOR][COLOR=SILVER]"rw"[/COLOR][COLOR=GREEN]/*read-write mode*/[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
          
          [COLOR=PURPLE]long[/COLOR] length [COLOR=BLACK]=[/COLOR] raf[COLOR=BLACK].[/COLOR]length[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
          String line[COLOR=BLACK];[/COLOR]
          [COLOR=NAVY]for[/COLOR][COLOR=BLACK]([/COLOR][COLOR=PURPLE]long[/COLOR] rPos[COLOR=BLACK]=[/COLOR][COLOR=ORANGE][B]0L[/B][/COLOR][COLOR=BLACK],[/COLOR] wPos[COLOR=BLACK]=[/COLOR][COLOR=ORANGE][B]0L[/B][/COLOR][COLOR=BLACK];[/COLOR] rPos[COLOR=BLACK]<[/COLOR]length[COLOR=BLACK];[/COLOR] raf[COLOR=BLACK].[/COLOR]seek[COLOR=BLACK]([/COLOR]rPos[COLOR=BLACK])[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK]{[/COLOR]
            [COLOR=GREEN][I]// READ[/I][/COLOR]
            line [COLOR=BLACK]=[/COLOR] raf[COLOR=BLACK].[/COLOR]readLine[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
            rPos [COLOR=BLACK]=[/COLOR] raf[COLOR=BLACK].[/COLOR]getFilePointer[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
    
            [COLOR=GREEN][I]// EDIT TEXT[/I][/COLOR]
            line [COLOR=BLACK]=[/COLOR] line[COLOR=BLACK].[/COLOR]replaceAll[COLOR=BLACK]([/COLOR][COLOR=SILVER]"\\D"[/COLOR][COLOR=BLACK],[/COLOR][COLOR=SILVER]"~"[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
            [COLOR=GREEN][B]/**
              Make sure new line.length() 
              does not exceed old line.length()
             */[/B][/COLOR]
            
            [COLOR=GREEN][I]// WRITE[/I][/COLOR]
            raf[COLOR=BLACK].[/COLOR]seek[COLOR=BLACK]([/COLOR]wPos[COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
            raf[COLOR=BLACK].[/COLOR]writeBytes[COLOR=BLACK]([/COLOR]line [COLOR=BLACK]+[/COLOR] NEWLINE[COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
            wPos [COLOR=BLACK]=[/COLOR] raf[COLOR=BLACK].[/COLOR]getFilePointer[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
          [COLOR=BLACK]}[/COLOR]
          raf[COLOR=BLACK].[/COLOR]setLength[COLOR=BLACK]([/COLOR]raf[COLOR=BLACK].[/COLOR]getFilePointer[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR] [COLOR=GREEN][I]// TRUNCATE[/I][/COLOR]
          raf[COLOR=BLACK].[/COLOR]close[COLOR=BLACK]([/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR] [COLOR=GREEN][I]// duh...[/I][/COLOR]
        [COLOR=BLACK]}[/COLOR][COLOR=NAVY]catch[/COLOR][COLOR=BLACK]([/COLOR]IOException x[COLOR=BLACK])[/COLOR][COLOR=BLACK]{[/COLOR]
          System[COLOR=BLACK].[/COLOR]err[COLOR=BLACK].[/COLOR]println[COLOR=BLACK]([/COLOR][COLOR=SILVER]"OMG! Now your file is corrupted!"[/COLOR][COLOR=BLACK])[/COLOR][COLOR=BLACK];[/COLOR]
        [COLOR=BLACK]}[/COLOR]
      [COLOR=BLACK]}[/COLOR]
    [COLOR=BLACK]}[/COLOR]
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  10. #10
    Join Date
    Jan 2009
    Posts
    90
    Rep Power
    0

    Default

    Java Code:
    		while(input.hasNext())
    			{
    				String s1 = input.nextLine();
            // WHAT? what are you trying to do?
    			    chars = s1.toCharArray(s1.split(" "));
    			}
    
    			for(int i=0; i<chars.length; i++)
    			{
            // err... no you can't compare a char to a string.
    				if(chars[i] == "John")
            // no such method for chars
    				chars[i].replaceAll(chars[i],"");
    			}
    WHAT? what are you trying to do?
    im trying to put each word in an array, i guess that is not a correct way.

    // err... no you can't compare a char to a string.
    If i successfully puting each word in an array i would comparing a string to string. i guess that failed too.

    // no such method for chars
    thanks! now i know =]

Similar Threads

  1. find and replace text from a text file
    By gezzel in forum New To Java
    Replies: 2
    Last Post: 09-19-2008, 05:04 PM
  2. [SOLVED] how to replace exact string in java
    By pankaj_salwan in forum New To Java
    Replies: 22
    Last Post: 07-08-2008, 10:28 AM
  3. string replace problem
    By soni in forum Advanced Java
    Replies: 8
    Last Post: 07-06-2008, 02:21 AM
  4. Find and replace ( in a String
    By hamish10101 in forum New To Java
    Replies: 6
    Last Post: 01-17-2008, 06:51 AM
  5. String replace method
    By venkata.tarigopula in forum Advanced Java
    Replies: 1
    Last Post: 07-10-2007, 09:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •