Is there a function to Search a Text File?

I am writing a program that will read data from a URL and then save that URL to a text file. I then need to be able to search the text file for certain strings and must know which line they appear on. I realize that I could read the text file in line by line looking for the string and then note the current line number. However, I need to search for 20-30 different strings in each URL and this would be very inefficient. I would really like some way to say:
int lineNumber = 0;
lineNumber = searchText("sometextfile.txt", str);
And have searchText return the lineNumber on which the String str was found. Alternately, if there is way to search a URL that would cut out the middle man of writing it to a text file first.
Any help would be greatly appreciated as I could not find this anywhere. Thanks.

I have done something similar to to this, but it depends on what you want to use it for. I was looking for specific data on websites and would copy that data into a database. So, I used regex to find the data on the site and copy it. I also had to use String Tokenizer in certain places to get the correct data sometimes.
orozcom

Similar Messages

  • Searching a text file and printing the line if found!

    Hi, Im fairly new to JAVA and have been googling this for hours and havent found any results that
    have helped me...
    Im looking to search a text file for a value that is in a that is delimited by colons
    eg 45787 : 398948 : 398884 : 398984
    IF that value is found I need to print this entire line and move it into a string.
    I can work out the delimit part, the problem for me is a)searching the text file
    and b) tell java to print that line only??
    Any help would be very very much appreciated
    Cheers
    James

      public void printCourses() throws Exception
                stuinput[] courseObjArray = new stuinput[10]; //Make sure this is the same as the ammount in the text
                   Scanner sc = new Scanner(new File("testfile.txt"));
                   int i=0;
                   boolean found = false;
                   while(sc.hasNextLine())
                   //Delimit this line with scanner
                   Scanner sc1 = new Scanner(sc.nextLine());
                   sc1.useDelimiter(":");
                   courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
                   i++;
                   }//while
                   for(int i1 = 0;i1 < courseObjArray.length;i1++)
                   System.out.println(courseObjArray[i1].courseCode);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println("-----------------");     
                   String courseCode2 = "courseObjArray[i1].courseCode";
                   if (courseCode2  == "12345")
                        System.out.println("working");
                   else{System.out.println("Not Found");}
           }hmmm just wondering why could this method always return a "Not Found"....if the text file had a whole bunch of values like this
    12345:Course1
    12344:Course2
    12343:Course3
    isnt it surposed to return 1 "Working"?? because there is a 12345 in on of the line, in the semi colon delimited line with 2 values, one being the course code, one being the course name??
    Given that there is 10 lines (from Array Object)

  • Is there any  function module to download pdf file

    is there any  function module to download pdf file
    WITH OUT GUI_DOWNLOAD FUNCTION MODULE.
    THANKS IN ADVANCED.

    Dear Laxman,
    Tryout the following Function Modules:
    (1)  CONVERT_ABAPSPOOLJOB_2_PDF --> convert abap spool output to PDF
    (2)  CONVERT_OTF --> Convert SAP documents (SAPScript) to other types.
    Example:
    CALL FUNCTION "CONVERT_OTF"
           EXPORTING    FORMAT                = "PDF"
           IMPORTING    BIN_FILESIZE          = FILE_LEN
           TABLES       OTF                   = OTFDATA
                        LINES                 = PDFDATA
           EXCEPTIONS   ERR_MAX_LINEWIDTH     = 1                  
                        ERR_FORMAT            = 2
                        ERR_CONV_NOT_POSSIBLE = 3
                        OTHERS                = 4.
    Regards,
    Abir
    Don't forget to award Points *

  • Is there any function module for converting text to hyperlink?

    Hello all,
              I am designing an application in BSP wherein the user can enter hypertext values for some
              of the data enteries in the database table. Is there any function module available for converting
              text into hypertext. Eg. if the user enters 'www.mypersonalwp.com' then it should convert this
              text value into a hyperlink.
    Thanks in advance.
    Gurmahima.

    Hi,
    Refer the given below link
    http://help.sap.com/saphelp_erp2004/helpdata/EN/85/ce25c2d7ae11d3b56d006094192fe3/content.htm
    Hope it helps you
    Thanks
    Arun Kayal

  • Binary search in text files

    Hi all,
    I'm thinking about how to implement a binary sort to get,given a key, a value from a text file with a list of words in order. I saw randomaccessfile for j2se and I know that this work it's usually done by seek functions but how to do the seek work without the File class , with only the InputStream and Reader? I'm talking about the j2me midp 2 cldc 1.1 api, is there some methods or class to use for this thing? How could be implemented a binary search in a text file resident in the /res dir or the JAR or which could be the problems that cannot make possible this staff? If there was something like seek one way could be that one of decide a common length of words to read so going to the half of the text file it's possible with simply multiplication, and the do the binary search things.But for now I haven't found any resources or help.
    I hope you can help me to understand, thank you

    Hallo all,
    it is NOT the problem to locate the text I need to find in the fmb, or fmx.
    The problem is that since I want to change not only the text but also some more code around I want to do this in Form Builder - Object Navigator. And I'm not able to discover in which trigger or procedure the text appears.
    I do not want to edit fmx, or fmb in a text editor because I suupose theer are some checksums hidden for the format.
    -duro
    BTW in FMT there is no code seen (only some binary) for v6i as it was in v4.5.

  • Is there a way to search for a file within a site defined in Dreamweaver?

    I know you can search for phrases within a file's code, but
    what if I have defined an extremely large site in Dreamweaver with
    thousands of files in it and then I search for a file with the
    phrase "contact" in it? Is there a way to do this in Dreamweaver or
    is there an extension that would add this functionality?

    On Thu, 24 Jan 2008 01:50:58 +0000 (UTC), "MartinUCSD"
    <[email protected]> wrote:
    >I know you can search for phrases within a file's code,
    but what if I have
    >defined an extremely large site in Dreamweaver with
    thousands of files in it
    >and then I search for a file with the phrase "contact" in
    it? Is there a way
    >to do this in Dreamweaver or is there an extension that
    would add this
    >functionality?
    Of course
    Edit | Find and replace
    put in the "content" in the Find box - select Find in Entire
    site and
    click Find all
    ~Malcolm N....
    ~

  • Search the text file using vbscript.

    Hi I have some data in my text file. Below is the content. Now I need to search the file whether it contains identityType as ApplicationPoolIdentity. Any help in vbscript???
     name:"example"
     queueLength:"1000"
     autoStart:"true"
     enable32BitAppOnWin64:"false"
     managedRuntimeVersion:"v2.0"
     managedRuntimeLoader:"webengine4.dll"
     enableConfigurationOverride:"true"
     managedPipelineMode:"Integrated"
     CLRConfigFile:""
     passAnonymousToken:"true"
     startMode:"OnDemand"
     [processModel]
       identityType:"ApplicationPoolIdentity"
       userName:""
       password:""
       loadUserProfile:"false"

    ok my solution is below,
    CONST ForReading = 1
    Dim File1
    Dim FileToRead
    Dim strLine
    Dim infoResult
    Dim strDir, objFile, returnvalue
    strDir = "C:\Scripts\"
    File1 = "sample.txt"
    FileToRead = strDir & File1
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(FileToRead, ForReading)
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
            if instr(strLine, "identityType") <> 0 then
              if instr(strLine, "LocalSystem") <> 0 then
                    infoResult = "Found"
                    exit do
                end if
            else
                infoResult = "Not Found"
            end if
    Loop
    objFile.Close
     Wscript.Echo infoResult    
    Set objFSO = Nothing
    Set objFile = Nothing

  • Insert data to MySQL when there is new data in the text file

    I have one log file, the log file will update its data (alarm type & datetime) when there is alarm. If I would like to write program to monitor the log file every minute, and insert the data to mysql when there is a new data in log file. Any Idea how to use java to write it ?
    Thanks !

    imagination21 wrote:
    Any Idea how to use java to write it ?Yes. But do you have a specific question? What's the problem?

  • Which app to read and search a text file?

    I have a text doc containing a little database.. I want to keep on my iPhone and read .. but I also need to search it. Does any App do this?

    Well you can upload it somehow and then read it online. On your mac, go to any page and make it a bookmark. Then, press the little "book" icon by your bookmarks and then click on the bookmark you just made. Then change the web address of the bookmark you just saved to...
    javascript:void%28s%3Dprompt%28%27Find%20text%3A%27%2C%27%27%29%29%3Bs%3D%27%28% 27s+%27%29%27%3Bx%3Dnew%20RegExp%28s%2C%27gi%27%29%3Brn%3DMath.floor%28Math.random %28%29*100%29%3Brid%3D%27z%27%20+%20rn%3Bb%20%3D%20document.body.innerHTML%3Bb%3 Db.replace%28x%2C%27%3Cspan%20name%3D%27%20+%20rid%20+%20%27%20id%3D%27%20+%20ri d%20+%20%27%20style%3D%5C%27color%3A%23000%3Bbackground-color%3Ayellow%3B%20font -weight%3Abold%3B%5C%27%3E%241%3C/span%3E%27%29%3Bvoid%28document.body.innerHTML %3Db%29%3Balert%28%27Found%20%27%20+%20document.getElementsByName%28rid%29.lengt h%20%20%27%20matches.%27%29%3Bwindow.scrollTo%280%2Cdocument.getElementsByName%28rid %29%5B0%5D.offsetTop%29%3B
    Then sync this bookmark to your iPhone. Finally, open the database page you uploaded to the web on your iphone and go to the bookmark you just saved. You should then be able to search the document. Tell me if it works.

  • Searching into text files

    Hi friends!
    I'm working with Oracle8i and using ConText Cartridge to make
    searches in some fields of a table. The problem is that this
    table has a field to store a file name that contains large text.
    This field has type VARCHAR(128). I don't know how to make
    searches in this field. Can anybody help me, please?
    Thank you all in Advance
    Carlos Moreno

    Hi friends!
    I'm working with Oracle8i and using ConText Cartridge to make
    searches in some fields of a table. The problem is that this
    table has a field to store a file name that contains large text.
    This field has type VARCHAR(128). I don't know how to make
    searches in this field. Can anybody help me, please?
    Thank you all in Advance
    Carlos Moreno

  • Is there any way to format a text file while writing it in java ?

    Heyya Fellas,
    I am working on a project and at the end of the process, the project should generate a report file in .txt format in the location prescribed by user. I am able to generate it and do all the processing but can i the report in a more presentable way. Like is there any method in java code so that we can make the text in the report file appear bold or italic while writing a file in java in runtime?
    Please help me.. any gist or click will be a favor.
    Thanks and Cheers
    Phoenix

    masijade. wrote:
    Text is text, nothing more, nothing less. Any "effects" to the text (i.e. bold, italic, underlined, striked, whatever) can only be acheived through some type of markup (i.e. html markup or rtf/pdf formats and the like). The text itself can never be bold or italic.
    If you are producing csv, then html style markup is a definate candidate, if you are producing reports than look into iText for creating pdf documents.I beleive dats it..
    Actually i am hitting a JSP's URL and it inturn calls a servlet and then the process takes place..
    and i generate the specified output file..
    The files are generated and every thig is working fine but i wanted to add that extra bit of a gloss to report.
    Well thanks for the response.

  • Problem using a vector of strings as patterns to search a text file

    Ideas? Goal is to use several patterns from one file to search for matches in a second file, one pattern at a time. I have added the file of patterns to a vector and created an iterator to grab each pattern successively. I also can effectively search for matches in the second file, but can't seem to find a way to combine them. I've tried nested while(s) in both orders without success.
    Thank you for any suggestions.

    It sounds to me like it should work. What does your search code look like?

  • Searching through text file

    Hi guys,
    I want to search for a string in a file then copy everything after it into a string array i guess, basically the requirement is that where i work we get letters they are usually a paragraph long what i want to do is just just copy those paragraphs into a variable and save them to a database with the date and time. if i can be pointed towards the write API or a sample code that would be highly appreciated.
    Thank you in advance.
    regards
    zeeshan

    Say your paragraphs are seperated by a empty line (\n)
    import java.io.*;
    public class New{
      public static void main(String args[]){
        try{
          new New().getParagraphs(args[0],args[1]);
        }catch(Exception ex){
          ex.printStackTrace();
      public String[] getParagraphs(String after, String fileName) throws Exception{
        File file = new File(fileName);
        if(!file.exists())
          throw new Exception("File not Found");
        else{
          BufferedReader br = new BufferedReader(new FileReader(file));
          String fileData = "";
          String temp = null;
          boolean canCopy = false;
          while((temp = br.readLine()) != null)
            if(canCopy)
              fileData += temp + "\n";
            else
              if(temp.indexOf(after) != -1){
                canCopy = true;
                fileData += temp.substring(temp.indexOf(after) + after.length()) + "\n";
        return fileData.split("\n");
    }Edited by: gtRpr on 2008/06/26 01:36

  • Search a text string to get location

    Is there any way to search a text string in a PDF file or a page of PDF file to get the location of this text string, say (x, y, width, height)?
    Thanks a lot for your help.

    I believe that there is an Assembler command to find text in a document. I think it is DocumentText and you have an attribute called withQuads that will give you 4 points that surround the text that you are looking for.
    I am going from memory so I would have a look at the DDX reference that comes with Assembler.

  • Search for text and font

    I have an 800 page pdf document to index and so far I have a script that will search for a list of keywords. But the text has large sections of code in a different font, and I think we would like to generate an index of just code examples. Is there a way to search for text of a given font in applescript? Something like
    set theSel to find text theText
    if the font of theSel is "Times"
    write to file, etc.

    Please do send a page, I might be able to spot where the font problem is coming from - but no guarantee Address is in my profile.
    You asked about the script formatter. red_menace of this forum wrote the script I use. To use it, you copy the script that you want to format to the clipboard and run the formatter. This then places the marked-up text in the clipboard so that you can paste it into the forum page.
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px; height: 340px;
    color: #000000;
    background-color: #FFDDFF;
    overflow: auto;">
    script formatter - formats the clipboard text for forum posting
    last reviewed January 19, 2009   red_menace[at]mac[dot]com
    Input: text read from the clipboard
    Output: formatted text copied to the clipboard
    set AppleScript's text item delimiters to " "
    -- some constants and switches
    property TextColor : "#000000" -- black  (see http://www.w3schools.com/tags/ref&#95;colornames.asp)
    property BackgroundColor : "#FFDDFF" -- a light plum/purple
    property BorderColor : "#000000" -- black
    property TheWidth : "width: 720px; " -- a width attribute  (deprecated in HTML 4.01)
    property UseWidth : true -- use the width attribute?
    property LineCount : 25 -- the number of lines before including the height attribute
    property TheHeight : "height: " & ((LineCount * 13.6) as integer) & "px; " -- a maximum height for the <pre> box
    property Emphasize : false -- emphasise (bold) the script text?
    property UseURL : false -- include a Script Editor message link?
    property AltURL : false -- use an alternate URL encoding?
    property ToolTips : {¬
    "this text can be pasted into the Script Editor", ¬
    "this text can be pasted into an Automator 'Run AppleScript' action", ¬
    "this text can be pasted into an Automator 'Run Shell Script' action", ¬
    "this text can be pasted into a HTML editor", ¬
    "this text can be pasted into a text editor", ¬
    "- none -"}
    property TooltipDefault : {item 1 of ToolTips} -- keep track of the last tooltip used
    property TempFile : "Script_Formatter_TempFile" -- a temporary work file
    try
    -- write the clipboard to the temporary file
    set TheClipboard to (the clipboard) as text
    if TheClipboard is in {"", space, tab, return} then return -- clipboard is (basically) empty
    set MyOpenFile to open for access ("/tmp/" & TempFile & ".txt" as POSIX file) with write permission
    set eof of MyOpenFile to 0 -- empty any previous temp file
    write TheClipboard to MyOpenFile
    close access MyOpenFile
    if UseURL then
    -- encode URL  (see http://developer.apple.com/documentation/Darwin/Reference/Manpages/man1/pydoc.1. html)
    do shell script "/usr/bin/python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' " & quoted form of TheClipboard
    -- add a link wrapper
    set URLtext to "applescript://com.apple.scripteditor?action=new&script=" & the result
    if AltURL then -- use an alternate URL encoding
    set URLtext to "Click here to [url=" & URLtext & "]open this script in the Script Editor[/url]:<br />"
    else -- use HTML anchor tag
    set URLtext to "Click here to <a href=\"" & URLtext & "\">open this script in the Script Editor</a>:<br />"
    end if
    set PromptText to ((count URLtext) as text) & " URL and "
    else
    set {URLtext, PromptText} to {"", ""}
    end if -- UseURL
    -- convert to HTML  (see http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/textutil .1.html)
    do shell script "cd /tmp/; /usr/bin/textutil -convert html -excludedelements '(html, head, title, body, p, span, font)' -encoding US-ASCII " & TempFile & ".txt"
    -- fix up some formatting and add a pre wrapper  (see http://www.w3schools.com/tags/default.asp)
    set HTMLtext to rest of paragraphs of (read ("/tmp/" & TempFile & ".html" as POSIX file))
    if (count HTMLtext) is less than LineCount then -- skip the height attribute
    set Height to ""
    else
    set Height to TheHeight
    end if
    set HTMLtext to FixCharacters from (HTMLtext as text) -- additional character encodings
    if UseWidth then
    set Width to TheWidth
    else
    set Width to ""
    end if
    if Emphasize then set HTMLtext to "<strong>" & HTMLtext & "</strong>"
    set HTMLtext to "<pre style=\"
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    margin: 0px;
    padding: 5px;
    border: 1px solid " & BorderColor & ";
    " & Width & Height & "
    color: " & TextColor & ";
    background-color: " & BackgroundColor & ";
    overflow: auto;\"
    title=\"\">
    " & HTMLtext & "</pre>
    -- assemble everything on the clipboard
    set TheResult to choose from list ToolTips ¬
    with title "Script Formatted" with prompt PromptText & ((count HTMLtext) as text) & " HTML characters will be placed on the clipboard (plus the following ToolTip):" default items TooltipDefault OK button name "OK" cancel button name "Cancel" with empty selection allowed without multiple selections allowed
    if TheResult is false then -- cancel button
    error number -128
    else -- add the selected title attribute (tooltip), if any
    set TooltipDefault to TheResult as text
    set Here to (offset of " title=" in HTMLtext) - 1
    set There to (offset of ">" in HTMLtext) - 1
    if TheResult is in {{}, "- none -"} then -- no tooltip
    set the clipboard to URLtext & (text 1 thru (Here - 1) of HTMLtext) & (text (There + 1) thru -1 of HTMLtext)
    else
    set the clipboard to URLtext & (text 1 thru (Here + 9) of HTMLtext) & TheResult & (text There thru -1 of HTMLtext)
    end if
    end if -- TheResult is false
    on error ErrorMessage number ErrorNumber
    log space & (ErrorNumber as text) & ":" & tab & ErrorMessage
    try
    close access MyOpenFile
    end try
    if (ErrorNumber is -128) or (ErrorNumber is -1711) then -- nothing (user cancelled)
    else
    activate me
    display alert "Error " & (ErrorNumber as text) message ErrorMessage as warning buttons {"OK"} default button "OK"
    end if
    end try
    to FixCharacters from TheText
    fixes (converts) formatting characters used in some message forums  (see http://www.asciitable.com/)
    parameters - TheText [text]: the text to fix
    returns [text]: the fixed text
    -- this list of lists contains the characters to encode - item 1 is the character, item 2 is the HTML encoding
    set TheCharacters to {¬
    {"!", "&#33;"}, ¬
    {"*", "&#42;"}, ¬
    {"+", "&#43;"}, ¬
    {"-", "&#45;"}, ¬
    {"[", "&#91;"}, ¬
    {"\\", "&#92;"}, ¬
    {"]", "&#93;"}, ¬
    {"^", "&#94;"}, ¬
    {"_", "&#95;"}, ¬
    {"~", "&#126;"}}
    set TempTID to AppleScript's text item delimiters
    repeat with SomeCharacter in TheCharacters
    if item 1 of SomeCharacter is in TheText then -- replace
    set AppleScript's text item delimiters to item 1 of SomeCharacter
    set the ItemList to text items of TheText
    set AppleScript's text item delimiters to item 2 of SomeCharacter
    set TheText to the ItemList as text
    end if
    end repeat
    set AppleScript's text item delimiters to TempTID
    return TheText
    end FixCharacters
    </pre>

Maybe you are looking for

  • **SOLUTION** DLLML.exe Fails to load at startup (application error)

    Hello everyone! I purchased the SB X-Fi Fatalty Champion Edition soon after release, and think this is the best card I have ever used to date. Absolutely love it, unbelievable sound. Now a year or two ago I noticed a certain file failing to load when

  • Degeneration of bulit-in HP netbook screen protectors

    I've been through about a dozen HP netbooks, and while I have found them very good I have come across a very troublesome development in many of the newer ones. At some point HP deceded to extend the bezel into a transparent screen protector. This is

  • Payement terms Baseline date

    Hi All, I had a billing document created on 01.04.09 and I am releasing the same to accounts on 05.04.09. Now my billing date will be 01.04.09 and payment terms C010 will start the calculation of the given 10 days from 01.04.09. But I need the start

  • Retrieving Reports from Cache

    10gAS 9.0.4.1 Reports 9.0.2.0.3 First Issue: I am trying to reuse reports from cache. I have caching turned on in my rep_<server>.conf file, and the following entry in my cgicmd.dat file: rep17: report=<report name>.jsp <parameter>=%1 desformat=pdf d

  • Oracle Database 10g Release 2 for HP-UX Itanium

    I cannot find this specific db in the Oracle downloads - there is one for RELEASE 1 but not Release 2. Does anyone know if there IS a release 2, and if not "out" yet when it will be?