3 Replies Latest reply on Feb 2, 2004 4:56 PM by 807582

    io stream

      how to count strings in any file by io stream
        • 1. Re: io stream
          read in the single bytes and check if the current byte is a word separator / a space char.

          count these separators and finally add 1.
          FileInputStream in = new FileInputStream("words.txt");
          byte current_byte;
          byte separator = " ".getBytes()[0];
          int gap_counter = 0;
          while((current_byte = in.read()) != -1) {
             if(current_byte.equals(separator)) {
          System.out.println((gap_counter+1) + " words found in file words.txt");
          to make sure that there are no multiple separators ("word1 word2 word3 word4 word5") you might first read in the whole file and use a StringTokenizer to get the number of words:
          FileInputStream in = new FileInputStream("words.txt");
          byte current_byte;
          String whole_file_text = new String();
          while((current_byte = in.read()) != -1) {
             whole_file_text += current_byte;
          StringTokenizer tokenizer = new StringTokenizer(whole_file_text, " ");
          System.out.println(tokenizer.countTokens() + " words found in file words.txt");
          • 2. Re: io stream
            • 3. Re: io stream
              First read the info from file. One way ....
              String str;
                             DataInputStream in = new DataInputStream(new FileInputStream("1.txt"));
                        }catch(FileNotFoundException e){}
                        catch(EOFException e){}
                        catch(IOException e){}

              if you just need to count words in the string (assuming space delimitation), easiest way to count words is this.......

              StringTokenizer st = new StringTokenizer(yourString);
              st.countTokens() should return thenumber of words in the string.

              If however, the delimiter is not space, use this approach....

              int index=0;
              int numOccurrences=0;
              index= str.indexOf("if",index);
              System.out.println("index is.."+index);
              if(index==-1) break;
              System.out.println("Num ..."+numOccurrences);