Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 07-05-2009, 02:05 AM
Member
 
Join Date: Jan 2009
Posts: 90
Rep Power: 0
PureAwesomeness is on a distinguished road
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

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.
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 07-05-2009, 05:34 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 07-05-2009, 06:00 AM
Member
 
Join Date: Jan 2009
Posts: 90
Rep Power: 0
PureAwesomeness is on a distinguished road
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?
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 07-05-2009, 06:13 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 07-05-2009, 06:31 AM
Member
 
Join Date: Jan 2009
Posts: 90
Rep Power: 0
PureAwesomeness is on a distinguished road
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?
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 07-05-2009, 07:33 AM
Senior Member
 
Join Date: Mar 2009
Posts: 376
Rep Power: 1
Singing Boyo is on a distinguished road
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)
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.
__________________
So you came along and found Java? Randomly?
Well then, you're just like me!
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 07-05-2009, 08:03 AM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 5,968
Rep Power: 7
Fubarable is on a distinguished road
Default
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.
Bookmark Post in Technorati
Reply With Quote
  #8 (permalink)  
Old 07-06-2009, 01:36 AM
Member
 
Join Date: Jan 2009
Posts: 90
Rep Power: 0
PureAwesomeness is on a distinguished road
Default
This is Singing Boyo's suggestion but the codes have errors
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

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.
Bookmark Post in Technorati
Reply With Quote
  #9 (permalink)  
Old 07-06-2009, 03:15 AM
angryboy's Avatar
Senior Member
 
Join Date: Jan 2009
Location: Javaland
Posts: 743
Rep Power: 2
angryboy is on a distinguished road
Default
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],"");
			}
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.
Code:
import java.io.*;
public class RandomAccessFileDemo {
  public static final String NEWLINE = 
    System.getProperty("line.separator");
  
  public static void main(String[] args){
    try{
      RandomAccessFile raf = new RandomAccessFile
          ("hey.txt"/*file-name*/,"rw"/*read-write mode*/);
      
      long length = raf.length();
      String line;
      for(long rPos=0L, wPos=0L; rPos<length; raf.seek(rPos)){
        // READ
        line = raf.readLine();
        rPos = raf.getFilePointer();

        // EDIT TEXT
        line = line.replaceAll("\\D","~");
        /**
          Make sure new line.length() 
          does not exceed old line.length()
         */
        
        // WRITE
        raf.seek(wPos);
        raf.writeBytes(line + NEWLINE);
        wPos = raf.getFilePointer();
      }
      raf.setLength(raf.getFilePointer()); // TRUNCATE
      raf.close(); // duh...
    }catch(IOException x){
      System.err.println("OMG! Now your file is corrupted!");
    }
  }
}
__________________
USE CODE TAGS--> [CODE]...[/CODE]
Get NotePad++ (free)
Bookmark Post in Technorati
Reply With Quote
  #10 (permalink)  
Old 07-06-2009, 03:38 AM
Member
 
Join Date: Jan 2009
Posts: 90
Rep Power: 0
PureAwesomeness is on a distinguished road
Default
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 =]
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


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


All times are GMT +2. The time now is 07:03 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org