Search for a word and return all the  lines (row) from the text file..

Hi all,
I need a help on how to search a string from the text file and returns all the lines (rows) where the searched string are found. I have included the code, it finds the indexof the string but it does not return the entire line. I would appreciate your any help.
public class SearchWord
     public static void main(String[] args){
     //Search String
     String searchText = "man";
     //File to search (in same directory as .class file)
     String fileName = "C:\\Workspace\\MyFile.txt";
     //StringBuilder allows to create a string by concatinating
     //multiple strings efficiently.
     StringBuilder sb =
     new StringBuilder();
     try {
     //Create the buffered input stream, which reads
     //from a file input stream
     BufferedInputStream bIn =
     new BufferedInputStream(
     new FileInputStream(fileName));
     //Holds the position of the last byte we have read
     int pos = 0;
     //Holds #of available bytes in our stream
     //(which is the file)
     int avl = bIn.available();
     //Read as long as we have something
     while ( avl != 0 ) {
     //Holds the bytes which we read
     byte[] buffer = new byte[avl];
     //Read from the file to the buffer
     // starting from <pos>, <avl> bytes.
     bIn.read(buffer, pos, avl);
     //Update the last read byte position
     pos += avl;
     //Create a new string from byte[] we read
     String strTemp =
     new String(buffer);
     //Append the string to the string builder
     sb.append(strTemp);
     //Get the next available set of bytes
     avl = bIn.available();
     catch(IOException ex) {
     ex.printStackTrace();
     //Get the concatinated string from string builder
     String fileText = sb.toString();
     int indexVal = fileText.indexOf(searchText);
     //Displays the index location in the file for a given text.
     // -1 if not found
     if (indexVal == -1)
          System.out.println("No values found");
     else
          System.out.println("Search for: " + searchText);     }
}

Hi, you can use servlet class and use this method to get the whole line of searched string. You can override the HttpServlet to treat that class as servlet.
public class ReportAction extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//write your whole logic.
BufferedReader br = new BufferedReader(new FileReader("your file name"));
String line = "";
while(line = br.readLine() != null) {
    if(line.contains("your search string")) {
        System.out.println("The whole line, row is :"+line);
}

Similar Messages

  • Created path and used trim but the line appears from the wrong side?

    Hey,
    I've created a rectangle by using the pen tool, then applied a stroke to it. I've then added "trim paths" and the end value at 0seconds is 0% and then at 5 seconds its at 100% however the line appears from the wrong side of the screen, basically it's reversed, yet the reverse path symbol is not ticked.
    The line is meant to appear from left to right of the screen with a 2px stroke, which will then have a mask applied to show a large black box appear from this line and fill the rest of the screen up.
    Anyone able to help me at all?
    Thank you.

    If you animated the start then animate the end. Simple as that.

  • Removing the Control Characters from a text file

    Hi,
    I am using the java.util.regex.* package to removing the control characters from a text file. I got below programming from the java.sun site.
    I am able to successfully compile the file and the when I try to run the file I got the error as
    ------------------------------------------------------------------------D:\Debi\datamigration>java Control
    Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repet
    ition
    {cntrl}
    at java.util.regex.Pattern.error(Pattern.java:1472)
    at java.util.regex.Pattern.closure(Pattern.java:2473)
    at java.util.regex.Pattern.sequence(Pattern.java:1597)
    at java.util.regex.Pattern.expr(Pattern.java:1489)
    at java.util.regex.Pattern.compile(Pattern.java:1257)
    at java.util.regex.Pattern.<init>(Pattern.java:1013)
    at java.util.regex.Pattern.compile(Pattern.java:760)
    at Control.main(Control.java:24)
    Please help me on this issue.
    Thanks&Regards
    Debi
    import java.util.regex.*;
    import java.io.*;
    public class Control {
    public static void main(String[] args)
    throws Exception {
    //Create a file object with the file name
    //in the argument:
    File fin = new File("fileName1");
    File fout = new File("fileName2");
    //Open and input and output stream
    FileInputStream fis =
    new FileInputStream(fin);
    FileOutputStream fos =
    new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(fos));
         // The pattern matches control characters
    Pattern p = Pattern.compile("{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    //Replaces control characters with an empty
    //string.
    String result = m.replaceAll("");
    out.write(result);
    out.newLine();
    in.close();
    out.close();

    Hi,
    I used the code below with the \p, but I didn't able to complie the file. It gave me an
    D:\Debi\datamigration>javac Control.java
    Control.java:24: illegal escape character
    Pattern p = Pattern.compile("\p{cntrl}");
    ^
    1 error
    Please help me on this issue.
    Thanks&Regards
    Debi
    // The pattern matches control characters
    Pattern p = Pattern.compile("\p{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;

  • Powershell search for a word and use the next word

    Here is the skinny.  I am trying to easily part through a event log of print jobs.  I export it to a CSV, grab only the events that pertain to what I need but I am stuck there.  Here is a sample of what I need help with.
    Microsoft Word - Test Print owned by user1 on computer1 was printed on printer1 through port
    Obviously document name, user1, computer1 and printer1 will be different in almost every case.  How do I parse through this and grab the username, computer and printer.  I was thinking search for "owned by", but how do I grab the name?
    Thanks for the help.

    ok now I am running into another issue.  Apparently the nuances of splitting by word seems to be los on me.
    when I do
    foreach ($job in $printjob) {        $test = $job.split("owned by")        echo $test}
    It will then split the line by each and ever "o", "w", "n", "e", "d", etc.....  I even tried $test = $job.split("'owned by'").  Any ideas?
    I feel like I should explain why this is happening.
    When you call $job.Split(), you're calling the .NET Split() method of the object System.String.
    If you look at the overloads of split (i.e., all the different ways you can call String.Split) - link here https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 -,
    you'll notice that the only way of calling String.Split() with a single parameter is if you pass a char[], an array of characters.
    Now, if you were coding in C# or VB.NET and you did... String.Split("owned by"), you'd get an error saying that it's expecting a char[] but you gave it a string.
    Powershell however is a bit 'smarter' and it tries to accommodate... It knows that the method expects a char[] and it knows you gave it a string, but it also knows how to convert it to a char[], so it does that, and that's what the method String.Split()
    receives.
    And what happens when the method String.Split() receives a char[]? It splits on every single character in that char[], as you've seen :)
    How to fix it? Well, there are two overloads that accept a string[], so you can use those. Now here's an interesting fact...
    In the same way that PowerShell converted a string to a char[] to accommodate the needs of the method you were calling, it can also convert a string into a string[], so you could do this:
    $job.Split("owned by", [System.StringSplitOptions]::None)
    You're passing it a string... and a [StringSplitOptions] object, so you expect it to call the third overload from the page I provided earlier.
    But if you run it... you still get the same stuff as before! What gives?
    Well, seeing as in this particular case there is an overload that receives char[] and another that receives string[] and you passed a string, which means PowerShell will always have to convert it into something anyway... You have no control
    over what PowerShell will decide to convert the string to. It could convert to char[] or to string[]. In this case, because the definition of the char[] method appears before the string[], that gets picked.
    So, finally... how to force PowerShell to pick the string[] overload? Well, don't give it a choice!
    $job.Split([string[]] "owned by", [System.StringSplitOptions]::None)
    So here I'm casting the string into a string[] before it gets passed to the method, so PowerShell does not need to perform any conversion itself and everything is right with the world.
    Hope this helps :)

  • OracleSOA - File Adapter - Correct mechanism to get the line number from the file

    We are using Oracle SOA process to read data from a file, process the data and write it to the database. SOA process is created using Oracle File Adapter to read the data, Oracle BPEL to transform & process the data and Oracle DB Adapter to write the data into the database.
    Oracle File Adapter uses native schema to process the fixed length data in the file. The number of rows in the file may exceed more than 500,000, to support processing of large files we use chunk size in the file adapter as 4000 rows. In each read operation, file adapter reads the data that matches to the schema, there might be few rejected rows as well.
    Oracle File Adapter property - jca.file.LineNumber gives me only the line number till what line the data is read. Is there any way to get the line number in the xml message, which exactly matches to the line number in the file.?
    Flat File Format: (Every file has one header, trailer and multiple data lines),
    HEADER02 -
    L01
    L01
    L01
    TRAILER02
    Line number is one of the crucial requirement in the development of the SOA service, this is used to back trace the information from which source and line the data has come.

    Hi Anshul,
    Thanks for sharing your thoughts.
    I am using DB adapter to insert the data into db.
    While doing the xsl transformation I can get the index of the message using position(), but that is not the correct way as there can be rejected lines by the file adapter.
    Even if I maintain a local counter variable, it will not consider rejected lines and increment that, which is not correct.
    Thanks,
    Ravindra

  • HT5043 My daughter was taking pictures in photo booth and now all of our photos from the iphoto library appear to be missing.  Any ideas how to recover them?

    Does anyone know how to recover or view pictures after importing photos from photo booth?  My daughter said that she was asked if she wanted to start a "new card".  Is this term familiar to anyone.  So sad to lose all our photos....

    Sorry - what exactly was done? iPhoto and PhotoBooth have no relation to each other -
    If she deleted the iPhoto libreary in error then take it out of the trash and put it back in the pictures folder - if the trash has been emptied then restore your backup of the iPhoto lbiarary - that is what backups are for - to protect against mistakes and failures
    LN

  • Wifi has suddenly stopped working. There is an exclamation mark which takes me to network diagnostics. This asks me for network name and password. This is different from the startup wizard which only asked for a WEP key and modem name. What to do?

    My wifi has suddenly stopped working on my iMac, after working fine for almost a year. There is an exclamation mark on the wifi bars and when I click it, it takes me to a network diagnostics page. This page asks me for my username and password for the wifi, which I don't have. It is different from the WEP key and modem name, which I originally used to set up my connection. I have not experienced any problems on all my other wifi-enabled devices. Ipod touch, iPad, MacBook all work fine. What should I do?

    The name is the name of the network you created on the router. The password is the WEP password. You shouldn't be using WEP at all, as it's insecure and also seems to cause connection failures. Use WPA 2 Personal. If your router doesn't support it, get a new one.

  • How to delete the duplicate rows from the table

    Hi,
    I have 2 tbales namely component, component_audit
    For each record in component table there are multiple entries in component_audit table.
    I need to keep the first record and delete the others from the component_audit table
    say for example
    select a.component_id,a.dt_ti_stamp,a.component_name,a.column_before,b.comments from component_audit a,component b where a.component_id=b.component_id
    ( on the above result set only I shold apply the actual delete query )
    PLease help me in this regards.
    Thanks.

    delete from component_audit a where dt_ti_stamp not in (select
                                            min(b.dt_ti_stamp)
                                       from
                                            component_audit b
                                       where
                                            a.component_id = b.component_id)

  • PI removing blank spaces at the end of the lines in a plain text file

    Hi -
    I have an interface that transfers a file via FTP. I defined both the sender and receiver to transfer either Text or Binary but the interface removes every blank space I have after the last character. The file is a fixed lenght file.
    Example:
    Original file:
    Hello world(space)(space)(space)(space)(space)(space)(space)(space)(eol)
    where (space) is the space character and (eol) is the end of line char.
    File after it is received.
    Hello world(eol)
    I already defined the parameter Row.fieldFixedLenghts with 10164 which is the lenght of the lines of the file.
    Any ideas why it may be happening?
    Thanks,
    Carlos.

    Hi -
    I tried both the parameters:
    xml.fieldContentFormatting
    structure.fieldContentFormatting
    The received file still has the problem. All the blank spaces are cleared out.
    The file is a plain text file not an XML file. May this be the issue?
    Thanks,
    Carlos.

  • How do I get itunes to recognize all of the music in my library. I backed up the library for 24.95 and not all of it went into the backed up library?

    How do you get Itunes to recognize all the music in your library when you buy the backup in the cloud? Alot of my  music was not backed up. These are songs I burned off my CD collection. Itunes Match did not recognize them either?

    *What am I doing wrong?*
    You moved it to the server.
    You should let iTunes do it.
    Point iTunes prefs to the new location.
    Menu Advanced -> Consolidate library.

  • I bought my kids an itouch...however, it snyced to my account.  Is there a way to create a separate account from them and remove all of my information from the touch?

    if i give my itouch to my son, how can i start from scratch with none of my info on it?  Additionally, i would like for him to have his own account but he isn't  old enoughby apple's rules, is there a way for him to have a sub account from mine?

    Hopefully you moved the entire iTunes Media (or iTunes Music) folder to a new path on your external drive. Copy your iTunes library folder out to the root of the external drive, e.g. X:\iTunes (where X: is your external drive), then move the media folder inside it. Hold down shift as you start iTUnes and keep holding untila asked to choose or create a library. Choose the library at X:\iTunes\iTunes Library.itl. Should all be good.
    Failing that, download and run my FindTracks script and point it at the new location of your media folder.
    tt2

  • Master Child tables how to get the latest rows from both

    Hi,
    Need some help with the sql. I have two tables Master & Child. In my Master table I have multiple rows for the same record and in the child table also multiple rows for the same master row how can I get the latest one's from both.
    For example Data in my Master table looks like
    CONT_ID                  SEQ_NUM        DESCRIPTION
    1                         189             Update 2
    1                         188             Update 1
    1                         187              NewNow in the child table for the same CONT_ID I may have the following rows
    CONT_ID                   UPDATED_DATE                                     STATUS
    1                        3/16/2010 2:19:01.552700 PM                          P
    1                        3/16/2010 12:29:01.552700 PM                         A
    1                        3/16/2010 12:29:01.552700 PM                         P
    1                        3/16/2010 12:19:01.552700 PM                         NIn my final query how can I get the row with seq_num 189 as it's the latest in Master table and from child table the row with status of P as it's the latest one based on the time. Here is the query i have but it returns the latest row from the child table only and basically repeats the master table rows as opposed to one row that is latest from both:
    Thanks

    Hi,
    You can use the analytic ROW_NUMKBER function to find the latest row for each cont_id in each table:
    WITH     got_m_rnum     AS
         SELECT     cont_id,     seq_num,     description
         ,     ROW_NUMBER () OVER ( PARTITION BY  cont_id
                                   ORDER BY          seq_num     DESC
                           ) AS m_rnum
         FROM    master_table
    --     WHERE     ...     -- any filtering goes here
    ,     got_c_rnum     AS
         SELECT     cont_id, updated_date,     status
         ,     ROW_NUMBER () OVER ( PARTITION BY  cont_id
                                   ORDER BY          updated_date     DESC
                           ) AS c_rnum
         FROM    child_table
    --     WHERE     ...     -- any filtering goes here
    SELECT     m.cont_id,     m.seq_num,     m.description
    ,     c.updated_date,     c.status
    FROM     got_m_rnum     m
    JOIN     got_c_rnum     c     ON     m.cont_id     = c.cont_id
                        AND     m.m_rnum     = c.c_rnum
                        AND     m.m_rnum     = 1
    ;If you'd like to post CREATE TABLE and INSERT statements for the sample data, then I could test this.
    If there happens to be a tie for the latest row (say, there are only two rows in the child_table with a certain cont_id, and both have exactly the same updated_date), then this query will arbitrarily choose one of them as the latest.

  • Deleting a row from the item table

    Hi All,
    I have a requirement where I need to put a button to delete the selected row from the item table and for this I have written the following code:
    DATA lo_nd_t_bseg TYPE REF TO if_wd_context_node.
        DATA lo_el_t_bseg TYPE REF TO if_wd_context_element.
        DATA ls_t_bseg TYPE wd_this->element_t_bseg.
        data: it_tab type table of wd_this->element_t_bseg.
      lo_nd_t_bseg = wd_context->path_get_node( path = `Z.T_BSEG` ).
      lo_el_t_bseg = lo_nd_t_bseg->get_element( ).
      lo_el_t_bseg->get_static_attributes(
        IMPORTING
          static_attributes = ls_t_bseg ).
        lo_nd_t_bseg = wd_context->path_get_node( path = `Z.T_BSEG` ).
        lo_el_t_bseg = lo_nd_t_bseg->get_element( ).
        IF lo_el_t_bseg IS not INITIAL.
          lo_nd_t_bseg->remove_element( lo_el_t_bseg ).
        ENDIF.
    Now the problem is although it's deleteing the selected line correctly but because of this I am losing one line on the screen for the user to enter... my form has a fixed number of lines and in my case it's 10... so everytime I am using deleting a line item I am losing one line to enter..... can you please tell me how can I avoid this?
    Edited by: rajatg on Aug 4, 2011 3:12 PM

    lets say...
    i have 1,2,3 documents
    i have cleared , document 2....
    1. when the user selects this record.... you can read the context_element....using the context element you can get the values and clear those values and set the blank values...
    when the user click on save ...you can have only those two records in the table.
    2. conitnue with your logic .... remove_element. once it is done ,,, create_element at the deleted index...
    3. when clicked on delete ...remove_element ( current code).... bind the table to the node... and you will have ur values

  • How do I select a row from the middle of a recordset?

    UserID QuestionID Answered
    10 9 N
    10 8 N
    10 7 N
    10 6 N
    10 5 Y
    10 4 Y
    10 1 Y
    From the table sorted by QuestionID DESC, how do I select the first row from the bottom going up with Answered value equal to 'N'?
    Which in the example above would be:
    10 6 N
    I need to select this row and get the QuestionID value equal to 6.
    Right now I have:
    select QuestionID
    from tblMap
    where Answered = 'N'
    and ROWNUM = 1
    order by QuestionID ASC;
    This always the top most row, which would be:
    10 9 N

    Here i used DUAL to generate a list of numbers for me.
    ME_XE?select *
      2  from
      3  (
      4     select row_number() over (order by col1 desc) as rn, count(*) over() as cnt, col1
      5     from
      6     (
      7        select level as col1 from dual connect by level <= 9
      8     )
      9  )
    10  where ceil(cnt/2) = rn
    11  /
                    RN                CNT               COL1
                     5                  9                  5
    1 row selected.
    Elapsed: 00:00:00.07
    ME_XE?Edited by: Tubby on Jul 8, 2009 1:47 PM
    Seems i misread the question :)

  • Read email adress from a text file then check the validity of them

    a text file has three lines, each line contains one email adress:
    [email protected]
    qwe@@ws.com
    wer//@we.net
    read the email address from a text file, then check which one is invalid, output the invalid email adress in the console.

    no 3 .umm, an email adress can have more than 2 '.'s in it,
    example:
    [email protected]
    would be a valid email address.
    To decide what a valid address is you'd need to parse it against the correct standard.
    I think however that javax.mail.internet.InternetAddress does this for you, check out the docs:
    http://java.sun.com/products/javamail/1.2/docs/javadocs/javax/mail/internet/InternetAddress.html
    even if it parses it may not be a valid address though in that it may not actually exist.

Maybe you are looking for

  • Puzzling problem

    I am using vs2008 and have created a crystal report (windows application).  The data shows up correctly on the report (detailed section) but when I creat a chart all of the values appear to be zero.  I created the chart in the report header, using a

  • [Solved] Linux 3.8.8 = 3.9.2 causes XBMC's NFS feature to fail

    Hey guys. Upgrading from Linux 3.8.8 => 3.9.2 cause the "Connect to a NFS share" feature in the XBMC application to fail with the error "RPC Packet not accepted by the server" Mounting the share via "# mount -t nfs4 192.168.1.100:/home/evan/multimedi

  • Moving from iPhone 2g to 3g, what do I need to know?

    Have 3g iPhone on way, got 2g at mo, what do I need to do? Also is there any way of accessing "officelive" accounts with iPhone browser?

  • Facetime with 3GS

    I currently have lots of ways of "talking" to people, including Skype.  With Skype, I can talk to another person, and IF either of us turns on a camera, the other person gets to see our image. I'm pretty sure tha answer to this is "no", but is there

  • Unable to modify/replace/unlock hosts file with admin account

    Hi all, I'm having a serious issue when trying to modify the hosts file in Yosemite 10.10.3 I already tried through the terminal with sudo commands, Get Info window, editing the file externaly and then trying to replace the original hosts with the ne