Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to count search words (keywords) in a text file in Java

1 Answer

0 votes
package javaapplication1;

import java.io.*;

public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        String[] words = { "stripos", "click", "substr", "save", "search", "sizeof" };
        int[] count = new int[] {0,0,0,0,0,0};
        String fileName = "d:\\url.php";

        try
        {
            File file = new File("d:\\url.php");
            FileReader fr = new FileReader(file);
            try (BufferedReader br = new BufferedReader(fr))
            {
                 String line;
                 int pos = 0;

                 while((line = br.readLine()) != null)
                 {
                     for (int i = 0; i < 6; i++)
                     {
                         while ( (pos = line.indexOf(words[i], pos)) != -1)
                         {
                            pos = pos + words[i].length();
                            count[i]++;
                         }
                     } 
                 }
                 for (int i = 0; i < 6; i++)
                    System.out.format("The word: %-10s appear %3d times in file: %s\n", words[i], count[i], 
                                                                                        fileName);

            }
            catch (Exception e)
            {
                   System.out.println(e.toString());
            }  
        }
        catch (Exception e)
        {
            System.out.println("Error reading file: " + e.getMessage());  
        }
    }
}

/*

run:

The word: stripos    appear   5 times in file: d:\\url.php
The word: click      appear  50 times in file: d:\\url.php
The word: substr     appear  14 times in file: d:\\url.php
The word: save       appear   4 times in file: d:\\url.php
The word: search     appear   7 times in file: d:\\url.php
The word: sizeof     appear   2 times in file: d:\\url.php

*/



answered Mar 11, 2015 by avibootz

Related questions

1 answer 175 views
1 answer 291 views
1 answer 199 views
1 answer 151 views
1 answer 145 views
1 answer 162 views
1 answer 163 views
...