![how to find word in file in jav how to find word in file in jav](http://javaonlineguide.net/wp-content/uploads/2015/05/javagrep2.png)
If returns value is null which means no value for that word in the map then we insert a ‘1’. If the word is found the map, the get method returns the value, otherwise it return null. We find integer value from the map using string word as a value. We use a foreach loop for the array of string. The key is our word and integer is a counter. Here map has string key and integer value. Map cannot contain duplicate keys each key can map to at most one value. Map is an interface provided by Java collection Framework. In our case, let’s split our string using single space. Split method takes a string regex and returns an array of String. Let’s split it first using split method in string. StringBuilder is mutable object and it’s much faster. So if the file is large, here its needed a lot of concatenation which is costly for immutable object. Using its readLine() method, we can read a single line at time in the loop rather than read character one by one.Īs this method reads all the text and returns as a single string, so a lot of concatenation is required for adding every single line to a String which is returned by this method.
![how to find word in file in jav how to find word in file in jav](http://3.bp.blogspot.com/-Wc2AcEj-S0k/T6_O00CucFI/AAAAAAAAAg4/AeA8UkQYzRA/s400/HTMLEditor_02_save.png)
There are some benefits using BufferedReader. And then create another object of BufferedRader and put a FileReader object argument to its constructor and FileReader ’s constructor takes the File object as its constructor argument. So first let’s create a file object and put the file name of its constructor argument.
![how to find word in file in jav how to find word in file in jav](https://i.ytimg.com/vi/VXrTfovZLzY/maxresdefault.jpg)
And then read the text file and return as a String. It will take a text file name with its path as string. Say they are, readTextFromFile() and findFirstNonRepeatedWord().įirst method is pretty straightforward. First one, we have to read text from file and then find the first non-repeated word in the text. Note: this problem is given by Therap Java Fest in their facebook page.įinding solution for this problem is quite easy. Write a simple java program to find out the first non-repeated word in the file. Problem # 1: Suppose you have a plain text file.