Find certain areas of text from a text file

Hello all java Gurus! I need your help on something I am trying to do in order to learn java. I am very newbie and please show mercy if I don't understand every answer you probably give me. Here is my problem. I have text file with certain areas I need to "isolate" (to insert the data in a jTable after I solve this first).
Let's say we have the following data in a text file:
FILE IS "A.txt"
***first***
this is 1 line in first
this is  2 line in first
this is 3 line in first
***second***
this is 1 line in second
this is  2 line in second
this is 3 line in second
***third***
this is 1 line in third
this is  2 line in third
this is 3 line in third
**************I now need to read the "segment" that start with " *** blablabab *** " and ends with " ************** " and store the lines of this segment to another text file "B.txt".
So "B.txt" has let's say this "segment".
***second***
this is 1 line in second
this is  2 line in second
this is 3 line in second
**************How can I do this? I know how to read/write from/to a text file with FileReader and BufferReader but I have no idea how to experiment with this. Is there anyone who can give me a hint or a help to start?
I am very new to java so be gentle :-)
Thank you very much in advance.
Kostas

Well this is a very good and I think efficient way to
do but unfortunately I don't have a clue about regex
and how they work. This is something I should learn.
With the expression you wrote I would have each text
block at a time? This will be stored then to an
Arraylist like above? If you have another idea please
suggest. I am interested in learning new tricks :-)
Thanks for your reply notivago!!!
KostasRegular expressions have a somewhat steep learning curve but they are worthy the effort, they are fast and powerfull text finding tools, the whole idea is that you search the text for some pattern. I will provide you a sample code, it is half way to solve your problem, you will have to make some minor adjustements to use it you your real application(none in the RE itself I hope).
To understand it, look at the Pattern class documentation and the Matcher class documentation in the API.
* SectionExtractor.java
* version 1.0
* 25/05/2005
package samples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
* @author notivago
public class SectionExtractor {
     * @param args
    public static void main(String[] args) {
        String text =
                 "***first***\r\n" +
                  "this is 1 line in first\r\n" +
                  "this is  2 line in first\r\n" +
                  "this is 3 line in first\r\n" +
                  "**************\r\n" +
                  "***second***\r\n" +
                  "this is 1 line in second\r\n" +
                  "this is  2 line in second\r\n" +
                  "this is 3 line in second\r\n" +
                  "**************\r\n" +
                  "***third***\r\n" +
                  "this is 1 line in third\r\n" +
                  "this is  2 line in third\r\n" +
                  "this is 3 line in third\r\n" +
        Pattern pattern = Pattern.compile( "\\*{3}(.+?)\\*{3}$(.*?)\\*{14}", Pattern.DOTALL | Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(text);
        matcher.find();
        System.out.println( "Header: " + matcher.group(1) );
        System.out.println( "Text Body: \n" + matcher.group(2) );
}The sample as is, runs and give you output that should be clear on how the expression works. Try running it.
May the code be with you.

Similar Messages

  • Find exact word in text file tht is present in an excel sheet

    Hi all,
    i want to find words in an text file.
    but the criteria is i want to search words which r already listed in another excel sheet and change the color of these word.
    i used FileInputStream
    and also BufferedInputStream
    cany anyone help me with this

    hi kajbj,
    can u plz tell me how to do in VBA then
    will find out the way to do in java
    Thanx

  • Is there a way to select a certain box of elements from a csv file and read that into LabVIEW?

    Hello all, I was wondering if there was a way to select only a certain "box" of elements from a .csv file in LabVIEW? I have LabVIEW 2011 and my main goal is to take two arrays and graph them against each other. I can import the .csv file just fine and separate each row and each column to be its own, but say I have an 8X8 but want to graph the middle 4X5 or something like that. Is there any way to extract an array without starting at the beginning and without ending at the end? Thank you in advance.
    Solved!
    Go to Solution.

    Hi Szklanam,
    as a CSV file is just a TXT file with a different suffix you can read a certain number of lines of that file. So you can limit the number of rows in your resultung array. To limit the number of columns you still have to use ArraySubset, so maybe it's a lot easier to read the full CSV file and pick the interesting spots with ArraySubset...
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • How to find out what was imported from a dump file

    Hi.
    I got the dump file from a group and they told me to import it. Import job went successfully without errors as following:
    Import: Release 9.2.0.6.0 - Production on Mon Oct 16 20:53:12 2006
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    Connected to: Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.6.0 - Production
    Export file created by EXPORT:V09.02.00 via conventional path
    Warning: the objects were exported by OPS$ORACLETS, not by you
    import done in US7ASCII character set and UTF8 NCHAR character set
    import server uses WE8ISO8859P1 character set (possible charset conversion)
    export server uses AL16UTF16 NCHAR character set (possible ncharset conversion)
    . importing OPS$ORACLETS's objects into SYS
    . importing BDS_APP's objects into BDS_APP
    Import terminated successfully without warnings.
    How do i find out what was imported from a dump file?

    another way would be to just list the contents of the dump file
    imp user/pass file=dumpfile show=Y

  • Pixels appear incomplete in certain areas within text. The words are blurry like the pixels haven't fully opened...

    text appears blurred only in certain areas. When you mouse over the text or highlight the text then remove the highlighting the text becomes crystal clear or sharp and will stay that way.

    Hello,
    Try disabling graphics hardware acceleration. Since this feature was added to Firefox, it has gradually improved, but there still are a few glitches.
    You might need to restart Firefox in order for this to take effect, so save all work first (e.g., mail you are composing, online documents you're editing, etc.).
    Then perform these steps:
    *Click the orange Firefox button at the top left, then select the "Options" button, or, if there is no Firefox button at the top, go to Tools > Options.
    *In the Firefox options window click the ''Advanced'' tab, then select "General".
    *In the settings list, you should find the ''Use hardware acceleration when available'' checkbox. Uncheck this checkbox.
    *Now, restart Firefox and see if the problems persist.
    Additionally, please check for updates for your graphics driver by following the steps mentioned in the following Knowledge base articles:
    * [[Troubleshoot extensions, themes and hardware acceleration issues to solve common Firefox problems]]
    * [[Upgrade your graphics drivers to use hardware acceleration and WebGL]]
    Did this fix your problems? Please report back to us!
    Thank you.

  • Find Change through external text file

    Hello folks
    I am bit pretty in InDesign scripting so could you please look into this.
    How can i change any particular text field in Indesign CS3 document from text file.
    I do have find change script but for each InDesign document specific text file is assigned.
    So each time i have to modify find change GREP property that is also repetetive of work. Is there any way to get find change information should be extract from external text file.
    Many Tanks in advance

    In the FindChangeByList script, you could customize the function myFindFile(myFilePath) {...} as to search the FindChangeList text file in the document location rather than the script location. That's an example. The question is: given a document, where will you have the corresponding FindChangeList?
    @+
    Marc

  • Find words within a text file

    Hey all.
    I am playing around with the idea of finding a line of text within a text file, by using scanner and some next methods.
    The way I am trying to get it to work is that one enters a string and the program then finds all the lines of text containing that
    user-entered string and then prints them.
    The text file in question contains names of University papers and their room numbers, quantity of students etc.
    Example:
    IBUS212     EALT006     1am     72     AL     LI     
    BMSC241     MCLT102     2     pm     8     AL     COOREY     
    My problem annoyingly enough seems to be that I can't think how one could compare the string entered to the lines of text being
    scanned in the text file.
    My latest go involved what you see in the code, scanning the examdata.txt file for a user-entered course number, using course.next();
    by going with the example above it would be IBUS212. The task was to then to find all of the lines containing that number and print them out using
    println (what I have tried with id and line) as well as the rest of that line eg: EALT006     1am     72     AL     LI .
       public void printCourse()
        try
            String details, input, id, line;
            int count;
            Scanner user = new Scanner(System.in);
            System.out.println();
            System.out.println();
            System.out.println("Please enter your course ID: ");
            input = user.nextLine();
            Scanner course = new Scanner(new File("examdata.txt"));
            course.next();
            course.nextLine();
            id = course.next();
            line = course.nextLine();
            if(input.equals(id))
                System.out.println("Your course times are: "  + id + "and" + line);
            else
              System.out.println("Your course does not exist."); 
            catch(IOException e)
                System.out.print("File failure");
      }Any advice/help/troubleshooting would be greatly appreciated.
    Edited by: AUAN on Aug 13, 2009 9:43 AM
    Edited by: AUAN on Aug 13, 2009 9:44 AM
    Edited by: AUAN on Aug 13, 2009 9:49 AM

    You'll want [to loop while|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html] the course Scanner has a next line and then print the line if it contains the entered text.
    For useful methods you can check the Javadoc of String and Scanner (use your browser search on keywords like 'next' or 'contains' to find them).

  • Finding strings in a text file?

    Hi! i'm learning to read text files. what i want to do with this program is to find word 1-3, 2-4, 3-5... and write them in a system.out.println. i found a program that opens files and count words, lines and characters and tried to adjust it do find three-word strings.
    i can compilate (hope that word exists) but when i run it, it says: Exception in thread "main" java.lang.NoSuchMethodError: main
    anyone who knows what this could depend on?
    This is what the code looks like:
    import java.io.*;
    import java.io.*;
    import java.util.*; //tillagd f�r att removeFirst4 skall funka
    import javax.swing.*; //tillagd f�r att removeFirst4 skall fungera
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    import java.lang.*;
    import javax.swing.*;
    public class AttLaesaEnFil2 {
         private static void samla(String name, BufferedReader in) throws
         IOException {
         String a;
         WordExtractor b;
    String c = " ";
    String d;
    WordExtractor e;
    String f;
    String g;
    WordExtractor h;
    String i;
    String j;
    String k;
    String l;
    String line;
    do {
                   line = in.readLine();
                   if (line != null)
    b = new WordExtractor(line);
         c = b.getFirst();
         d = b.getRest();
         e = new WordExtractor(d);
         f = e.getFirst();
         g = e.getRest();
         h = new WordExtractor(g);
         i = h.getFirst();
         j = h.getRest();
         k = c + f + i;
         l = c + " " + f + " " + i;
         System.out.println("The first three words are: " + l);
         a = b.getRest();
    while (line != null);
              System.out.println("Klart!");
              private static void samla(String fileName) {
              BufferedReader in = null;
              try {
                   FileReader fileReader = new FileReader(fileName);
                   in = new BufferedReader(fileReader);
                   samla(fileName, in);
              } catch (IOException ioe) {
                   ioe.printStackTrace();
              } finally {
                   if (in != null) {
                        try {
                             in.close();
                        } catch (IOException ioe) {
                             ioe.printStackTrace();
         private static void samla(String streamName, InputStream input) {
              try {
                   InputStreamReader inputStreamReader = new InputStreamReader(input);
                   BufferedReader in = new BufferedReader(inputStreamReader);
                   samla(streamName, in);
                   in.close();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
    Thanx in advance!

    this may be a stupid question but i'll give it a
    shot. ...do i replace my private static void with
    public static void or do a add the public?Whether you replace one of your methods or create a new one is up to you, but you have to have a method with this exact signature:
    public static void main(String[] foo) {
    }(The variable name can be different of course)

  • What are the text files that suddenly showed up in the Preferences folder?

    I just noticed a group of text files in the Preferences folder that I haven't noticed before. All of them were created within a 3-minute period on 12/31/2008. The names are in sets of 4 or 5 that follow this scheme:
    np_334572current
    np_334572services
    np_334572servicesnew
    np_334572sets
    np_334572system
    The default app to open these is Property List Editor.
    They haven't been modified since they were created, even though I've been adding, deleting, and modifying apps and their preferences since then. Anybody know what they are? Can or should I delete these?
    Thanks in advance.

    Dick,
    To be honest I don't know what program they are related to. However If the files are located in ~/Library/Preferences (Where is ~ = your home directory) Then You should be safe in moving/deleting them, at worst you will have to reset the settings in one of your apps. What that folder is mainly used for is say for example you have your dock show/hide it self. That will be saved to a plist file in the preferences folder. If you delete or move the dock's plist out of there your dock on your next login will go back to the default view of Mac OS.
    Now To be honest you don't have to move/delete those files that are there, especially since at most you will probably reset some of the preferences you set in an application. But its up to you. Also you could always move it first to see what app it is and either move it back or delete it later.
    Hope that helps,
    Weston

  • Are plain text files treated differently in SP 2010 than MOSS 2007?

    We just moved to SP 2010 a week ago.  A user just contacted us asking why the files she accesses are not displaying.
    When she accessed these plain text files in MOSS 2007, they displayed within IE as a full page of text.
    When she accesses these now in SP 2010, she is prompted to download the file.
    These files do not end in .txt - they are names such as 2013.09.20 or whatever.
    Is there a way to configure 2010 to display, without any interpretation, plain text files within the browser?
    Thank you.

    Hi ,
    According to your description, my understanding is that you could not access the txt files with browser after migrading to SharePoint 2010..
    Whether this issue occurred if you upload a new txt file to a library.
    In my testing, everything worked well. The Open Documents in Client Applications by Default feature was acitve, and in the Library Settings->Advanced settings, ‘Use the server default(Open in the client application)’ was selected. When I clicked the file
    name, it promted a dialog like the below, I selected ‘Read-Only’, and clicked OK, the file could open with browser.
    Please go to IE->Tools->Internet Options->Programs->Manage add-ons, enable all add-ons related to SharePoint, compare the result.
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • Find line number in text file

    Hi all,
    I need to find the line numbers on a file where a particular string matches.
    for example:
    A lazy cat
    A strong cat and it is black
    Black is not good
    So I will match for the word black and it will give the numbers say line 2 and 3 it found the match.
    I am using the code:
    try{
        // Open the file that is the first
        // command line parameter
          FileInputStream fstream = new FileInputStream("c:\\test.log");
        // Get the object of DataInputStream
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
         String[] arr= null;
        //Read File Line By Line
       String regex = "black";
       while ((strLine = br.readLine()) != null)   {
        // Split the sentence into strings based on space
           arr = strLine.split("\\s");
       if (arr[0].equalsIgnoreCase("black"))
          System.out.print("match found");
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(strLine);Thanks in advance.

    camellia wrote:
    I need to find the line numbers on a file where a particular string matches. Then declare a variable for line count. Find where you read in a line. Finally increment this variable each time a line is read.
    It isn't rocket science.
    Mel

  • I added an e-mail account to my iphone using microsoft exchange; all went fine. I then deleted a number of contracts from my phone that I did not want there and find they are now gone from my e-mail account on my computer.  Can I retrieve them?

    I added an e-mail account to my iphone using microsoft exchange; all went fine. I then deleted a number of contacts from my iphone that I did not want on my phone. when I went into my e-mail account on my computer the contacts were deleted from there also.  Will I be able to retrieve them?  If so, how?  Thank you.

    In the device sync pages select Photos on the top at the right.
    Un tick Sync Photos
    Apply

  • How do I remove certain data being imported from a php file

    I have data being loaded from a php into an xml class.
    My host (which is free for testing purposes) keeps adding data to the php file which causes errors.  I need to know how I can delete this extra text before I put the data into an XML class so I do not get the error.  I did a trace of the data and this is what comes up below.  I need everything below the </data> tag to be removed but do not know how to do this.  Can someone please help me.
    <?xml version='1.0' encoding='UTF-8'?><data>
        <google rate='21' />
        <yahoo rate='3' />
        <msn rate='2' />
        <tv rate='10' />
        <diger rate='4' />
    </data>
    <!-- www.000webhost.com Analytics Code -->
    <script type="text/javascript" src="http://analytics.hosting24.com/count.php"></script>
    <noscript><a href="http://www.hosting24.com/"><img src="http://analytics.hosting24.com/count.php" alt="web hosting" /></a></noscript>
    <!-- End Of Analytics Code -->
    Thanks,
    Jason

    in your load complete function:
    var s:String=e.target.data;
    var xml:XML=XML(s.split("<!-- www.000")[0]));

  • How to convert a HTML files into a text file using Java

    Hi guys...!
    I was wondering if there is a way to convert a HTML file into a text file using java programing language. Likewise I would also like to know if there is a way to convert any type of file (excel, power point, and word) into text using java.
    By the way, I really appreciated the help that you guys gave me on my previous topic on how to extract tests from a pdf file.
    Thank you....

    HTML files are already text files. What do you mean you want to convert them?
    I think if you search the web, you can find things for converting those MS Office files to text (or extracting text from them, as I assume you mean).

  • Error in opening text file in JSF

    Hello,
    I am developing a Web application using JavaServer Faces Beta Version 1.0 and the Web application needs to open a text file. I used a Java class called by a backingbean class to open the text file.
    The problem is that the system cannot find and read the text file.
    The system shows the following errors.
    Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: javax.faces.el.EvaluationException: java.lang.RuntimeException: Could not
    read text file test.txt: java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:207)
    root cause
    javax.faces.FacesException: javax.faces.el.EvaluationException: java.lang.RuntimeException: Could not read
    text file test.txt: java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
         com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:83)
         javax.faces.event.ActionEvent.processListener(ActionEvent.java:57)
         javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:974)
         javax.faces.component.UICommand.broadcast(UICommand.java:274)
         javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:217)
         javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:316)
         com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:80)
         com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:171)
         javax.faces.webapp.FacesServlet.service(FacesServlet.java:196)
    note The full stack trace of the root cause is available in the Tomcat logs.
    I would like to ask how to open text file in the JSF framework.
    Thank you in advance.
    regards,
    oscar

    This is not a JavaServer Faces related issue. Anytime you try to open disk files in a web application, you need to use absolute pathnames. You have no control over what the current directory of our servlet container is set to.
    If the file you're reading is actually inside your web application (say, "test.txt" is in a subdirectory "files" ), you can get access to an input stream for it, in a portable way, by calling the getResourceAsStream() method on ServletContext. From an event handler, that might look like this:
      ServletContext sc = (ServletContext) FacesContext.getCurrentInstance().
        getExternalContext().getContext();
      InputStream stream = sc.getResourceAsStream("/files/test.txt");Craig McClanahan

Maybe you are looking for

  • Macbook to Sony Bravia 40 inch HDTV

    I am connecting my Macbook to my Sony Bravia HDTV via a Mini Dvi port/VGA adapter to a SVGA cable. However, nothing happens. It appears as though my TV doesn't recognize anything....Can anybody help?

  • HT2311 How do I install a previous version of iTunes for MacBook Pro?

    i'm trying to help out my friend who has recently purchased an old MacBook Pro ... he has a 2007 MacBook pro and everything works - done all updates etc ... BUT! (theres always a but isnt there ... ) I cant update the latest iTunes because the softwa

  • Can i use a window computer as a virtual PC?

    Hi, thanks in advance for your answers. I have an extra windows computer that is just collecting dust. Can i use the computer as a virtual PC with my macpro running lion? just got parrallels 7, thinking i could just transfer some of my older virtual

  • XI - Idoc scenario

    Hi, We use File <-> XI -> IDoc scenario. XI picks the Text file from the fileserver & we have BPM to do the intial validations. If the validation fails, then the file is again sent back to the fileserver by attaching a trailer record to the file. If

  • Cannot change font size when highlighted. All font changes. How do I correct this?

    Frustrated as to why when I highlight a single word to change font size or style every word on the page follows the adjustment. I need to be able to change words individually with font, size and color.