• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

Deleting a block of a string from a text file

Good morning, how are you all doing? I was wondering if someone could help me with something basically what I want to do is lets say I have this in a text file
Header|||||TEXT|||
Header1|||||.... so so on so


then another block of data
Header|||||TEXT1||
Header1||||||||.....so so on

Now what I want to do is read that file and if I find the Header with the TEXT1 in it then remove it from that file. Is that an easy thing to do in Java. Thanks

CRS
0
Corey_819
Asked:
Corey_819
  • 14
  • 14
1 Solution
 
zzynxSoftware engineerCommented:
Read in the file line by line.
Write the lines one by one to another file
Stop writing to the other file if you found that specific header
Start writing again if the end of that header is found
0
 
CEHJCommented:
If the file is small enough to read into memory, you can use the following class and treat it like a List:

import java.io.*;
import java.util.ArrayList;

/**
 *  A utility class the allows a text file to be
 *  treated as a collection of Strings
 *
 * @author     CEHJ
 * @created    29 February 2004
 */
public class StringList extends ArrayList {

  /**
   *Constructor for the StringList object
   */
  public StringList() {
    super();
  }

  public void read(InputStream in) {
    read(new InputStreamReader(in));
  }


  public void read(Reader r) {
    String line = null;
    BufferedReader in = null;
    try {
      in = new BufferedReader(r);
      while ((line = in.readLine()) != null) {
        add(line);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      try {
        in.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

  /**
   *  Constructor for the StringList object
   *
   * @param  fileName  The file to open
   */
  public void read(String fileName) {
    try {
      read(new FileReader(fileName));
    }
    catch(IOException e) {
      e.printStackTrace();
    }
  }

  /**
   *  Save the String to named file
   *
   * @param  fileName  The name of the file to save to
   */
  public void save(String fileName) {
    PrintWriter out = null;
    try {
      out = new PrintWriter(new FileOutputStream(fileName), true);
      for (int i = 0; i < size(); i++) {
        out.println((String) get(i));
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      if (out != null) {
        out.close();
      }
    }
  }

}
0
 
Corey_819Author Commented:
How would I know i found that specified header. If I use readline('\n\r') that will tell me when I get to the next header but not the |TEXT1| postion part of that header. put how do I read each postion in that string? Thanks for all your help guys.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
zzynxSoftware engineerCommented:
Using String functions like indexOf()
0
 
zzynxSoftware engineerCommented:
if ( readLine.indexOf("TEXT1")!=-1 ) {
  // the line has "TEXT1" in it
}
0
 
Corey_819Author Commented:
Exception in thread "main" java.lang.NoClassDefFoundError: Read/java

I am sorry this is probably silly question however I am still learning Java why am I getting this error above?
0
 
Corey_819Author Commented:
Disregard last question I figured out what I was doing wrong. :)
0
 
Corey_819Author Commented:
One more thing fellows. I guess I should have mentioned what exactly I was trying to do. I only want to find the line with TEXT1 in it that begins with MSH| would I just put an && statment in my if(readline.indexOf("TEXT1") !=-1 && readline.indexOf("MSH") !=-1)? Thanks for you help:)
0
 
zzynxSoftware engineerCommented:
if ( readLine.startsWith("MSH|") && readline.indexOf("TEXT1")!=-1 )
0
 
zzynxSoftware engineerCommented:
The equivalent is

      if ( readLine.indexOf("MSH|")==0 && readline.indexOf("TEXT1")!=-1 )

In words:
The string "MSH|" is found at position 0 in the string (=the beginning)
and
The string "TEXT1" is found "somewhere" in the string
0
 
Corey_819Author Commented:
I am sorry to bother you but I am still really learning Java. Now zzynz what you said worked prefect but it only reads that MSH| line nothing under it which coud be PV1|
                                             DG1|
Then another MSH| comes up again and the code does work but it misses basically the same start of lines as above? Basically I am asking how do i get it to read that MSH| reapeatedly like it is now and look for the TEXT1 but read all the lines underneatht the MSH| and then read the next MSH| to check for the TEXT1 again. Thanks for all your help. This is really helping me learn it.
0
 
Corey_819Author Commented:
Here is the example of my while I have been working with

while(!eof){
            String line = buff.readLine();
            if ( line == null)
                  eof = true;
            
            else if(line.startsWith("MSH|") && line.indexOf("EMH") !=-1)
            
              System.out.println(line);
            }
            buff.close();
0
 
Corey_819Author Commented:
Basically I am sure I could put a whole bunc of line.startsWith("the start of the line "|) but that seems like really poor coding. There has to be a better way
0
 
zzynxSoftware engineerCommented:
First a remark: you don't have to check for an EOF yourself. readLine() will just return null if EOF is reached.

As I said in my previous comment:
>>Stop writing to the other file if you found that specific header  
set some boolean flag
        beginFound = true;

>>Start writing again if the end of that header is found
If I understand you well, the end of a header is marked just by finding a new header (isn't it?)

         boolean beginFoud = false; // somewhere at the beginning of the read

         if ( beginFound ) {  // THE Header is already found previously
            if ( line.startsWith("MSH|" )  // another header starts here so:
              beginFound=false;            // "close" the previous header
         } else if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1) ) { // THE header is found
            beginFound = true;        // Make sure all further lines are treated as belonging to THE header
            System.out.println(line);
         }

0
 
Corey_819Author Commented:
Thanks for the tip on the eof I didn't know that.

Basically it is marked by a CR(in hex) and LF(in hex) then the new header starts. If I understand you right your saying with the above code it will check if the MSH| has been found already anf if it has the bool is true and it will print the rest my headers untill it encounters another MSH| then it will check to see if the indexOf EMH is in the line? Am i following it right?
0
 
zzynxSoftware engineerCommented:
You got that right.

But, the code needs a small correction:

         if ( beginFound ) {  // THE Header is already found previously
            if ( line.startsWith("MSH|" )  // another header starts here so:
              beginFound=false;            // "close" the previous header
         }
         if ( !beginFound ) {
             if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1) ) { // THE header is found
               beginFound = true;        // Make sure all further lines are treated as belonging to THE header
               System.out.println(line);
            }
         }

Explanation: if the next header is found, it also have to be checked for containing "EMH"
0
 
Corey_819Author Commented:
One the explanation the EMH will only be in MSH| now where else, well if it is I don't care I just need to check the MSH| line for the EMH positon index.
0
 
Corey_819Author Commented:
while(!eof){
            
            String line = buff.readLine();
            
            if(beginFound)
            {
                  if(line.startsWith("MSH|"))
                  
                        beginFound = false;
            }
            if(!beginFound)
            {
                  if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1)
                  {
                        beginFound = true;
                        System.out.println(line);
                  }
            }
            }
Here is my while loop it is still only reading the MSH| Do i have a syntax issue.
0
 
zzynxSoftware engineerCommented:
>> Here is my while loop it is still only reading the MSH|
You mean it is still only printing out the line containing MSH| ;°)

Of course, I forgot an extra System.out.println():

        while(!eof){
           
           String line = buff.readLine();
           
           if(beginFound)
           {
                if(line.startsWith("MSH|"))
               
                     beginFound = false;
           }
           if(!beginFound)
           {
                if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1)
                {
                     beginFound = true;
                     System.out.println(line);
                }
           }
           else System.out.println(line);  // <<<<<<<<<<<<<<<<< I forgot this
     }
0
 
Corey_819Author Commented:
if(beginFound)
            {
                  if(line.startsWith("MSH|"))
                     beginFound = false;
                     System.out.println(line);
            }
            if(!beginFound)
            {
                  if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1)
                  {
                        beginFound = true;
                        System.out.println(line);
                  }
            }
            }
Now if I do this I get the other lines that belong to the MSh| but the MSH| prints twice and I have an error with the if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1) blank is not found. probably need to throw an exit in there. I will try that.
0
 
zzynxSoftware engineerCommented:
Please see my previous comment
0
 
Corey_819Author Commented:
Thank you sorr for the reduntant question I didn't see the comment. I was just putting the println in the wrong place. I need to check if the line is null or the  if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1) doesn't meet and I need to exit the while loop where would I need to put that because right now i get a null pointer error which makes since becuase I need ot quit when I am done looking for  if (line.startsWith("MSH|") && line.indexOf("EMH") !=-1) and reading the lines under neath it.
0
 
zzynxSoftware engineerCommented:
Use

String line;
while( (line = buff.readLine())!=null )
 
    // all what is in your current while loop
}
0
 
zzynxSoftware engineerCommented:
Well, that's a whole bunch of info for 80 points isn't it? ;°)
0
 
zzynxSoftware engineerCommented:
Thanks for accepting
0
 
Corey_819Author Commented:
Thanks man that is it. I am learning java day by day. I am use to C++ so I am just trying to get the syntax and how it works down. Thanks have a great day. :)
0
 
Corey_819Author Commented:
I know I am sorry I wish I hav more points I would give you 500 I just didn't have much. I didn't mean for it to be this much info. Thanks though:) I will hook you up if I post another question again.
0
 
zzynxSoftware engineerCommented:
>> I am learning java day by day
Success
0
 
zzynxSoftware engineerCommented:
>> I know I am sorry I wish I hav more points I would give you 500 I just didn't have much.
No worries. Glad I could help.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 14
  • 14
Tackle projects and never again get stuck behind a technical roadblock.
Join Now