Hi everybody
I have a little question. I am using JFileChooser to open file and then process it.But the thing is its only works for txt file. What are the other ways to open all ither text files. Plus if would be really helpful if you would tell me how to process pdf files.
/**Theis program prompts user to open file
* then it counts and displays number of tokens.
*
*
*
*/
import java.util.*;
import javax.swing.*;
public class WordCounter {
// main map Keys are elements and Values are number of elements
private Map<String, Integer> map = new HashMap<String, Integer>();
private Scanner file;
public static void main(String[] args) {
new WordCounter();
}
public WordCounter() {
openFile();
createFileMap();
displayFileMap();
}
// this method opens file
public void openFile() {
JFileChooser myChooser = new JFileChooser();
int status = myChooser.showOpenDialog(null);
try {
file = new Scanner(myChooser.getSelectedFile());
}
catch (Exception e){
System.err.println("Can not open file");
System.exit(0);
}
}
//creates a Map
public void createFileMap() {
//read the file, line by line
while(file.hasNextLine()) {
// put the current line into str
String str = file.nextLine();
// breaks a line into tokens
StringTokenizer tokenizer = new StringTokenizer(str);
//check if there are more tokens
while(tokenizer.hasMoreTokens()) {
// assign current token to the word
String word = tokenizer.nextToken();
/*if Map has current word add 1 to the maps value
if no then associated current word with value 1*/
if(map.containsKey(word)) {
int count = map.get(word);
map.put(word, count +1);
}
else
map.put(word, 1);
}
}
}
//display map
public void displayFileMap() {
//returns a Set view of the keys contained in map
Set<String> keys = map.keySet();
System.out.println("\nMap contains elemets: \nKeys\t\tValues");
//Sort keys
Set<String> sortedKeys = new TreeSet<String>(keys);
//print each key and its value
for(String key : sortedKeys)
System.out.printf("\n%-10s%10d", key, map.get(key));
// display the map size
System.out.printf("\n\n%-10s%5d\n%-10s%11b",
"size of map is :", map.size(),
"map isEmpty: ",map.isEmpty() );
}
}