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)

Similar Messages

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • 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

  • How to write Strings in a text file with BufferedWriter

    I've got a Vector object full of Strings objects, I'm interested in wrinting these Strings in a text file with a BufferedWriter , I would apreciate some code, thank you

    http://java.sun.com/products/jdk/1.2/docs/api/java/io/BufferedWriter.html
    "PrintWriter out = new PrintWriter(new BufferedWriter((new FileWriter("foo.out")));"

  • How to find a string in a text file

    i'll have a text file in the following format and from this this type of file i've to get source URL i.e in the following file http://www.consolidatorshopper.com/patheo/Mall/prices.asp
    and also i've to get POSTdata querystring i.e in the following file from cosolidateorname...... to &conid6=7
    hope you people understood my problem
    i'll be very thankful if u people help me
    BEGIN HEADER
    source:http://www.consolidatorshopper.com/patheo/Mall/prices.asp
    POSTdata:consolidatorname=IF&AgentID=37344&SubAgentID=31030&LoginType=SUBAGNT&LoginConfirm=yes&ManageAccount=&CustomAccount=6&PALPowerSearch=2&ShowConsolidatorsOnPricesPage=0&PALHomePage=http://www.consolidatorshopper.com&PMarkup=0&PALLoginText=<B>Specific%20Consolidator%20Search:</B><BR>%20Click%20on%20the%20desired%20region%20on%20the%20map.<BR><BR><B>Power%20Search:</B><BR>To%20search%20all%20consolidators%20simultaneously%20click%20on%20the%20button%20below.%20However,%20not%20all%20consolidators%20currently%20participate%20in%20the%20Power%20Search.&PALrelativeLoginURL=&PALrelativeBookingURL=&[email protected]&SiteID=3&MallOwnerMarkupFlat=&conidselected=16&powersearch=2&iscontinentselected=1&Continent=USDomestic&Source=1&CRSName=AP&[email protected]&ConsolidatorURL=http://www.patheo.com&ConsolidatorPhone=714-677-0929&ConsolidatorFax=714-908-7110&ConsolidatorFullName=Patheo&noofconselected=7&amadeusconidstring=&flagamadeus=1&PowerSearchConsolidatorstring=&PublishedCRS=&APPseudoCity=&SBPseudoCity=&AMLogin=&AMPassword=&AMCorpID=&AMCatNo=&ConsolidatorFares=1&PublishedFares=0&PublishedConsolidator=0&PreferencedConsolidator=&Arciata=&dep_from=MIA&dep_to=LON&ret_from=LON&ret_to=MIA&dep_month=08&dep_day=08&dep_year=2003&dep_weekday=Thu&txtLengthOfStay=7&ret_month=08&ret_day=15&ret_year=2003&ret_weekday=Thu&dep_time=12P&ret_time=12P&triptype=RoundTrip&simpleclass=Economy&srchAirline=&adultno=1&childno=0&infantno=0&conid0=11&conid1=97&conid2=1&conid3=86&conid4=5&conid5=94&conid6=7
    BEGIN INFORMATION
    TimeStamp:datetime:date()
    BEGIN ACTION
    startafter:<tr valign=middle bordercolor=#ffffff>endat:</table>
    pattern:<font face='Arial, Helvetica, sans-serif' size='2'>[^<]*
    $1:SYMBOL:TEXT
    $2:INDEX:TEXT
    $3:CLOSING:FLOAT
    $4:CHANGE:FLOAT:StripHTMLTags()
    $5:CHANGEPCT:FLOAT:StripHTMLTags()
    BEGIN DO

    Hi, this is my fourth post to forum.java.sun.com and my final one for the day, so I can allow feedback to emerge on my compliance or lack thereof with the conventions of the board.
    Fortunately, I have picked up the skill of telepathy and so am able to answer your question. :)
    In your processLine(String line) method or equivalent, you can do something like this:
    if (line.indexOf("source:") == 0) {
       source = line.substring(6, line.length());
    } else if (line.indexOf("POSTdata:") == 0) {
       postdata = line.substring(9, line.length());

  • 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).

  • How to find largest number from text file

    I am using the "Read from text file" block to read the data from my .txt file into labview.  It is now in string format.  I have many numbers in the file.  
    For example:
    0.45
    0.35
    0.12
    1.354
    1.56
    2.89
    5.89
    0.56
    That is what a text file might look like.  I want to find which of these numbers is largest, and do calculations with that number.  I am having trouble with strings/number formats/arrays, etc.  Thanks
    Solved!
    Go to Solution.

    The spreadsheet functions and VIs typically work on strings representing numbers separated by delimiters.  This is a typical way to save a "spreadsheet" (of numbers) to a text file, for example .csv files.  These are quite versatile and powerful functions.  Spend a bit of time becoming familiar with them because you may find yourself using them a lot.
    Lynn

  • 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

  • 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

  • Writing a string into a text file

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    public class Main {
    public static void main(String[] args) {
    String result;
    result = "testtest";
    try {
    PrintStream ps = new PrintStream(new FileOutputStream("D:\\test\\output.txt"));
    ps.println(result);
    ps.close();
    } catch (Exception e) {
    System.out.println(e);
    I have a couple of string to write into text file
    ---- for example--
    String test1="aaa";
    String test2="bbbb";
    String test3="c";
    String test4="dd";
    --- condition to write into text file....
    test1 has to write between 1 - 5 position.
    test2 has to write between 6 - 15 postition.
    test3 has to write between 16 - 10 position.
    test4 has to write between 11 - 15 position.
    how can i write those strings into a certain position?
    how can i write those strings for 3 times in a text file?(make 3 rows)

    figure out how write them into a string, then use my helper util class like this:
    String str = "some\nstuff\nhere";
    ASCIIFile file = new ASCIIFile("c:/somefile.txt");
    file.setContents(str);
    //done, file written!code for ASCIIFile can be found here:
    http://www.doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
    change its package to work with your codes

  • How to search a String within a text file ?

    ************** text file ****************
    Good bye good
    bye good bye
    good bye
    good bye good
    bye good
    ************** Input and Output ****************
    Input: good bye
    Output:
    total strings Matched: 5
    whichlinesmatched: 2
    whichlinesmatched: 2
    whichlinesmatched: 3
    whichlinesmatched: 4
    whichlinesmatched: 5
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    ** but the desired output is 3, and only line 2, 3, 4 matched
    ** Could you please have further help about this? Thank you.
    ************** the codes****************
    import java.io.*;
    public class Tokenize{
    public static void main( String args[] ){
    int maxNumberOfLine = 1000; //the maximium number of line in data file for input
    String fileName = "test"; // file name for data input
    String stringForCount = "good bye"; // specified word for counting
    int totalStringMatched = 0; // number of word matched
    int[] whichLineMatched; // line number for each word matched
    whichLineMatched = new int[maxNumberOfLine];
    // Input string (stringForCount) has been stored in a string array, wordForCompare[]
    // For example: stringForCount = "good bye"
    int stringLength = 2;
    String wordForCompare [] = { "good" , "bye" };
    // wordForCompare[0] = good
    // wordForCompare[1] = bye
    int wordFromFile;
    StreamTokenizer sttkr;
    try{
    FileInputStream inFile = new FileInputStream(fileName); //specifying the file to be opened
    Reader rdr = new BufferedReader(new InputStreamReader(inFile)); //assigned a StreamTokenizer
    sttkr = new StreamTokenizer(rdr);
    sttkr.eolIsSignificant(false);
    System.out.println("Searching for word : " + stringForCount );
    while( (wordFromFile = sttkr.nextToken()) != StreamTokenizer.TT_EOF)
    System.out.println( "going looping through file, token is: " + sttkr.sval );
    if(sttkr.sval.equals(wordForCompare[0])){
    if (stringLength == 1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1]=sttkr.lineno();
    } else {
    for (int p=1; p < stringLength; p++) {
    wordFromFile = sttkr.nextToken();
    System.out.println( sttkr.sval );
    if (!(sttkr.sval.equals(wordForCompare[p])))
    break;
    else if (p==stringLength-1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1] = sttkr.lineno();
    } // end of else
    } // end of for-loop
    } // end of else
    System.out.println( " total strings Matched: " + totalStringMatched );
    } // end of if
    }//end of while for wordFromFile
    for( int i = 0; i < 10; i++)
    System.out.println( "whichlinesmatched: " + whichLineMatched<i> );
    } catch(Exception e) {} //end of try
    }

    A small change to roopa_sree's code, this code fails if there are multiple occurences of the search string in the same line. Make this small change to correct it,import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    public class WordCounter {
         public static void main(String args[]) throws Exception {
              if(args.length != 1) {
                   System.out.println("Invalid number of arguments!");
                   return;
              String sourcefile = args[0];
              String searchFor = "good bye";
              int searchLength=searchFor.length();
              String thisLine;
              try {
                   BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
                   String ffline = null;
                   int lcnt = 0;
                   int searchCount = 0;
                   while ((ffline = bout.readLine()) != null) {
                        lcnt++;
                        for(int searchIndex=0;searchIndex<ffline.length();) {
                             int index=ffline.indexOf(searchFor,searchIndex);
                             if(index!=-1) {
                                  System.out.println("Line number " + lcnt);
                                  searchCount++;
                                  searchIndex+=index+searchLength;
                             } else {
                                  break;
                   System.out.println("SearchCount = "+searchCount);
              } catch(Exception e) {
                   System.out.println(e);
    }Sudha

  • How to output strings to an text file and excel file

    Hi guys,
    I am writing a simple application taht process some string inputs from user using a simple GUI. The GUI consists of a series of
    textfields which the user can enter names, age, addresses....etc
    Once they complete filling up that GUI form, they click SUBMIT. All the values will then be read. These strings are then required to be output to 2 files
    1. To a text file which I can open it and read it anytime I wish.
    2. To an excel file which follows a specific format. That is, all names will be written to column B, all ages will be written to column C...etc
    The programme is expected to keep running allow the user to enter details of multiple persons(some 300 sets of data of different persons) until he clicks on End program.
    Please advise how I can output the strings to
    1. Text file
    2. Excel file.
    Many many thanks. I need this for one of my project which is due so so soon...... :((
    Regards
    David

    1. Text file
    See link to "Documentation - Tutorials" on the left
    side of this page.
    2. Excel file
    Dont try to write the real excel format (if you want
    to do it soon).
    - write data to a plain text file.
    - Use tab stops for separation of values.
    - Name file as excel file. (*.xls)
    If you double click this file, excel will import data
    and insert it to a table in the right order by
    itself.
    Excel can save this as real .xls now.
    Anyone here with a better idea? (Try to learn by
    myself)good thing to know for the excel tip :)
    thx

  • How to replace a string in a text file?

    Hi All,
    i read one text file and based on that i replaced the old character with the new string but it doesnt works.do any one of you have idea on this?
    My Code:
    String newPassword=(String) getInputText1().getValue();
    String password=(String)getSimNo().getValue();
    String sampleText = (String) getMobileNo().getValue();
    FileReader fr =new FileReader("c:/newLogin.txt");
    BufferedReader br =new BufferedReader(fr);
    String record=br.readLine();
    while (record !=null)
    String[] afterSplit=record.split(":");
    for (int p = 0; p < 1; p++) {
    String userName=afterSplit[1];
    String passWord=afterSplit[3];
    if(userText.equals(userName) && password.equals(passWord)) {
    passWord.replaceAll(passWord,newPassword);
    System.out.println("password: " + password +" changed to : "+ newPassword +" successfully");
    record =br.readLine();
    sample fiile in the text:
    userName:sebas:password:navin
    userName:sebas1:password:navin1

    All readLine does is copy a line of the file into a local variable. Change the copy as you will, the file won't change.
    You need to write a new version of the file, with the altered lines. Then, if required, you can delete the original file and rename the new file to the old file name.

  • Finding multiple strings in a text file and deleting the entire line

    Get-Content c:\output-Copy.txt | Where-Object {$_ -notmatch 'something1', 'something2', 'something3', 'something4' } | Set-Content temp.txt
    Above is the program that when it has 1 argument in the -notmatch part will find the specific string and delete the entire line. I need to be able to use multiple strings for my search, I am totally drawing a blank on this and I know its something REALLY
    simple but my brain is fried. The above code will work IF i only leave 'something1' and delete the rest. I need to find MULTIPLE matches and remove them all at once, what is a good way to accomplish this.

    You can use an alternating regex, like this:
    Get-Content c:\output-Copy.txt |
    Where-Object {$_ -notmatch 'something1|something2|something3|something4' } |
    Set-Content temp.txt
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Searching for a string in given text file

    Hi,
    I have two strings and i need to search the entire file for the strings and highlight the lines between the strings
    say, for example,
    hi this is xyz
    i am a begineer in java
    can i have some help in this issue please
    i gave 'hi' and 'can' i need the three lines to be highlighted
    can you give me an idea about this.
    how to proceed
    thanks all in advance
    Edited by: anub on Feb 6, 2009 3:24 AM

    Here's an idea. Find a link to the java API. Create a utility class with a method to read a file and a method to write a file. Look in java.io for this. That should keep you busy for a while and give you something specific to ask questions about. Next, create a GUI class and put a button on it. Figure out how to make a button click open a "FileChooser" or "JFileChooser" (Look in the api for that) Imagine that these need to talk to each other so figure out what parameters are needed. After you've done that then figure out how the user is going to enter the two search criteria (something that acts like a text field). Choose a GUI class that supports text highlighting. Display all the information that the user would like to know e.g. The name of the file selected to parse, the name of the file to write, and whether the strings were found successfully.
    kr
    walker

Maybe you are looking for

  • Create own idvd theme?

    How do you create your own them? Special SW? Please advice.

  • HD requires repair, but OSX disk will not mount

    When I run Verify Disk on Disk Utility my PowerMac 2.7 Dual (bluetooth keyboard, mouse) gives a message reporting "Failure on Exit" and as follows: Verifying volume "Macintosh HD" Checking HFS Plus volume. Checking Extents Overflow file. Checking Cat

  • Looks Like the iPad 3G Wait is Over

    Looks like the very last day of the month for iPad 3G orders.......why not just say Last Day of the Month instead of Late April. It's all about the hype I suppose. Well now at least we all know. My order status still says "Ships: Late April". http://

  • Imp Changes are needed in Nokia Belle

    I am using Nokia E7 since last 10 months. Symbian Anna and Belle are released in between. I have seen lot of differences between Anna and Belle. The following differences are also compared with normal phones also. Here I have mainly focused on issues

  • Share an AirPort Disk over WAN

    Hi guys, While browsing a blog I noticed that some people are confused with the process on setting up an AirPort disk for use over the internet using Wide Area Bonjour or Wide Are Network. I ended up throwing together a little PDF that will guide you