Java : Reading words from a File ?
When I was developing an algorithm for one of my assignment I had to read a String from a file and then separate all the words in that String .I tried to implement it using several methods .But most of them were really annoying !! :( . So after Googling for sometime I found out a nice method using the Regex facility in Java :)
I hope you are familiar with how to read a String from a file .:) Are you ? Oh! You are NOT :(
Then Look at this .
So here what kind of process we do ? We just separate all the words in that String.OK
So you know String class have a method as split.We can use it here.
split method returns a array of String .So by the above line we can separate all the words which have a SPACE between them .But that is not enough ...Is it ? What will happen to the words separated by commas,question mark ...etc (all the punctuations ).
So this is where Regex helps us out.It has some pre-defined Strings which we can use in split method .String "\\W" stands for all the NON WORD CHARTERERs .
The above code will give the exact output you need.Then you can use that String array for further process. Happy Coding !!!
I hope you are familiar with how to read a String from a file .:) Are you ? Oh! You are NOT :(
Then Look at this .
String str;
BufferedReader in = new BufferedReader(new FileReader(YOUR FILE PATH HERE));
while ((str = in.readLine()) != null) {
YOU CAN PROCESS YOUR STRING HERE
}
So here what kind of process we do ? We just separate all the words in that String.OK
So you know String class have a method as split.We can use it here.
String[] wordArray=str.split(" ");
split method returns a array of String .So by the above line we can separate all the words which have a SPACE between them .But that is not enough ...Is it ? What will happen to the words separated by commas,question mark ...etc (all the punctuations ).
So this is where Regex helps us out.It has some pre-defined Strings which we can use in split method .String "\\W" stands for all the NON WORD CHARTERERs .
String[] wordArray=str.split("\\W");
The above code will give the exact output you need.Then you can use that String array for further process. Happy Coding !!!
Comments
Post a Comment
Leave your ideas