---
title: "Read a .txt file and return a list of words with their frequency in the file"  
description: "Read a .txt file and return a list of words with their frequency in the file"  
author: "Anonymous User"  
published: 2014-12-30  
updated: 2014-12-30  
canonical: https://www.mindstick.com/forum/12829/read-a-txt-file-and-return-a-list-of-words-with-their-frequency-in-the-file  
category: "java"  
tags: ["java", "file"]  
reading_time: 3 minutes  

---

# Read a .txt file and return a list of words with their frequency in the file

I have this so far but it only prints the .txt file to the [screen](https://www.mindstick.com/forum/33644/loading-screen-during-ajax-call):\
[import](https://www.mindstick.com/blog/294/how-to-import-or-export-sql-server-table-data-in-ms-excel-sheet-using-c-sharp-code) java.io.*;\
[public](https://www.mindstick.com/blog/11097/java-access-modifiers-the-public-and-the-private-modifiers) class ReadFile { public [static void](https://www.mindstick.com/interview/2715/can-we-write-static-public-void-instead-of-public-static-void) main([String](https://www.mindstick.com/articles/1527/string-split-in-c-sharp)[] args) throws IOException { String Wordlist; int Frequency;\
File file = new File("file1.txt"); BufferedReader br = new BufferedReader(new [InputStreamReader](https://www.mindstick.com/forum/161307/what-is-the-role-of-inputstreamreader-in-java-input-handling)(new FileInputStream(file))); String line = null;\
while( (line = br.readLine()) != null) { String [] [tokens](https://answers.mindstick.com/qa/92537/what-are-tokens) = line.split("\\s+"); System.out.println(line); } }}Can [anyone help me](https://www.mindstick.com/forum/331/can-anyone-help-me-out-how-to-use-session-concept) so it prints a word list and the words frequency?

## Replies

### Reply by Samuel Fernandes

Do something like this. I'm assuming only comma or period could occur in the file. Else you'll have to remove other punctuation characters as well. I'm using a TreeMap so the words in the map will be stored their natural alphabetical order\

```
  public static TreeMap<String, Integer> generateFrequencyList()    throws IOException {    TreeMap<String, Integer> wordsFrequencyMap = new TreeMap<String, Integer>();    String file = "/tmp/lorem.txt";    BufferedReader br = new BufferedReader(new FileReader(file));    String line;    while( (line = br.readLine()) != null){         String [] tokens = line.split("\\s+");      for (String token : tokens) {        token = removePunctuation(token);        if (!wordsFrequencyMap.containsKey(token.toLowerCase())) {          wordsFrequencyMap.put(token.toLowerCase(), 1);        } else {          int count = wordsFrequencyMap.get(token.toLowerCase());          wordsFrequencyMap.put(token.toLowerCase(), count + 1);        }      }    }    return wordsFrequencyMap;  }  private static String removePunctuation(String token) {    token = token.replaceAll("[^a-zA-Z]", "");    return token;  }
```

main method for testing is shown below. For getting the percentages, you could get count of all the words by iterating through the map and adding all the values and then do a second pass for getting the percentages. By the way, if this is part of a larger work, you could also take a look at apache commons math library for calculating Frequency distributions. If you use their Frequency class, you can keep adding all the words to it and then get the descriptive statistics at the end.\

```
  public static void main(String[] args) {    try {      int totalWords = 0;         TreeMap<String, Integer> freqMap = generateFrequencyList();      for (String key : freqMap.keySet()) {        totalWords += freqMap.get(key);      }      System.out.println("Word\tCount\tPercentage");      for (String key : freqMap.keySet()) {         System.out.println(key+"\t"+freqMap.get(key)+"\t"+((double)freqMap.get(key)*100.0/(double)totalWords));          }    } catch (Exception e) {      e.printStackTrace();    }  }
```


---

Original Source: https://www.mindstick.com/forum/12829/read-a-txt-file-and-return-a-list-of-words-with-their-frequency-in-the-file

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
