Showing posts with label program. Show all posts
Showing posts with label program. Show all posts

Tuesday, October 29, 2013

E-mail in Java

This is a simple E-mail in Java program. You can use it to send message with multiple attachments to multiple recipients at the same time. Before you use the program to send e-mail message, you will need to configure the mail. The configuration form allows you to enter the outgoing server name, port, user name and password to log in the server. For security reason, your password is encrypted. The configuration file (mailconfigs.con) is stored in your current working folder. You can configure the email by going to File menu->Setup Configuration...One you configured the mail correctly, you do not need to configure it again later.

configure e-mail


After you configured the mail, you will need to input the From address (your e-mail address), the recipients' e-mail addresses, subject, and message of the mail. Bcc, Cc e-mail addresses, and file attachments are optional.



In Java, it is easy to send e-mail by using the Apache Commons Mail api. You will download the Apache Commons Mail api from its website. This api depends on the Java Mail api. You can download Java Mail api from here. After downloading the two api, extract the zip files and add the jar files (commons-email-1.3.2.jar and javax.mail.jar) to the Java Build Path in the Eclipse.

In the Commons Mail api, there two classes that can be used to send e-mail message. One class is SimpleEmail. The SimpleEmail class is used to send e-mail message without attachment. Another class is called MultiPartEmail. This class is able to send e-mail message with attachments. Like the SimpleEmail class, the MultiPartEmail class has methods that allow you to configure e-mail in your Java code.

MultiPartEmail email=new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,password);
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);

There are other methods that you will use to set the From e-mail address, To e-mail addresses, Bcc e-mail adddress, Cc e-mail addresses, subject, message, and attachment of the mail.

//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipient's (to) e-mail address
email.addTo(Toadd);
//add recipient's (Bcc) e-mail address
email.addBcc(Bccadd);
//add recipient's (Cc) e-mail address
email.addCc(Ccadd);
//add file attachment
email.attach(new File(path));

//send the email
email.send();

Here is the complete code of the E-mail in Java program.

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;


class UI extends JFrame implements ActionListener{
JTextField textfrom;
JTextField textto;
JTextField textbcc;
JTextField textcc;
JTextField textsubject;
JTextArea textmessage;
JLabel lblstatus;
JTextField txtserver;
JTextField txtport;
JTextField txtuser;
JPasswordField txtpwd;
DefaultListModel<String> listmodel;
MultiPartEmail email;
ArrayList<String> configs;
JFrame frame;
UI(String title){

Container cont=getContentPane();
setTitle(title);
setResizable(false);
setSize(new Dimension(650,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic('F');
JMenuItem itemserver=new JMenuItem("Mail configure...");
itemserver.addActionListener(this);
JMenuItem itemexit=new JMenuItem("Exit");
itemexit.addActionListener(this);
mfile.add(itemserver);
mfile.add(itemexit);
mbar.add(mfile);
setJMenuBar(mbar);

JPanel panelmain=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblfrom=new JLabel("From:");
textfrom=new JTextField(30);
JButton btadd=new JButton("Send");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lblfrom);
panelnorth.add(textfrom);
panelnorth.add(btadd);
GridBagLayout gbl=new GridBagLayout();
JPanel panelcenter=new JPanel(gbl);
GridBagConstraints gc = new GridBagConstraints();
JLabel lblto=new JLabel("To:");
textto=new JTextField(30);
JLabel lblbcc=new JLabel("Bcc:");
textbcc=new JTextField(30);
JLabel lblcc=new JLabel("Cc:");
textcc=new JTextField(30);
JLabel lblsubject=new JLabel("Subject:");
textsubject=new JTextField();
JButton btatt=new JButton("Attach");
btatt.addActionListener(this);

listmodel=new DefaultListModel<String>();
JList<String> attlist=new JList<String>(listmodel);
attlist.setVisibleRowCount(5);

gc.fill = GridBagConstraints.BOTH;
       gc.weightx = 1.0;
       gbl.setConstraints(lblto, gc);
       gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textto, gc);
      panelcenter.add(lblto);
panelcenter.add(textto);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblbcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textbcc, gc);
      panelcenter.add(lblbcc);
panelcenter.add(textbcc);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
   gbl.setConstraints(textcc, gc);
      panelcenter.add(lblcc);
panelcenter.add(textcc);


gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblsubject, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textsubject, gc);
      panelcenter.add(lblsubject);
panelcenter.add(textsubject);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(btatt, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gc.gridheight = 2;
       gbl.setConstraints(attlist, gc);
      panelcenter.add(btatt);
panelcenter.add(attlist);

gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weighty = 1.0;
lblstatus=new JLabel("");
lblstatus.setForeground(Color.RED);
gbl.setConstraints(lblstatus, gc);
panelcenter.add(lblstatus);


JPanel panelsouth=new JPanel(new FlowLayout(FlowLayout.LEFT));
panelsouth.add(new JLabel("Message:"));
textmessage=new JTextArea(15,50);
textmessage.setWrapStyleWord(true);
JScrollPane scroll=new JScrollPane(textmessage);
panelsouth.add(scroll);

panelmain.add(panelnorth);
panelmain.add(panelcenter);
panelmain.add(panelsouth);
cont.add(panelmain);
setVisible(true);
configureMail();
}
public void configureMail(){
readConfigs();
if(configs.size()>2){
setEmailConfigs(configs.get(0),Integer.parseInt(configs.get(1)),configs.get(2),configs.get(3));

}
}

public void actionPerformed(ActionEvent e){
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
if(e.getActionCommand().equals("Send")){
String from=textfrom.getText();
if(textto.getText().length()>0)
Tos=textto.getText().split(", ");
if(textbcc.getText().length()>0)
Bccs=textbcc.getText().split(", ");
if(textcc.getText().length()>0)
Ccs=textcc.getText().split(", ");
String subject=textsubject.getText();
String message=textmessage.getText();

if(from.length()>0 && Tos.length>0 && subject.length()>0 && message.length()>0) {
Th th=new Th(from,Tos,Bccs,Ccs,subject,message);
th.start();

}
else{
JOptionPane.showMessageDialog(this,"From, To, Subject, and Message cannot be blank.");
textfrom.requestFocus();
}

}
else if(e.getActionCommand().equals("Attach")){
selectFile();
}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
else if(e.getActionCommand().equals("Mail configure...")){
JPanel p=new JPanel(new GridLayout(5,1));
txtserver=new JTextField("Enter outgoing server");
txtport=new JTextField("Enter server port");
txtuser=new JTextField("Enter user name");
txtpwd=new JPasswordField("Enter password");
JButton bt=new JButton("Save and Close");
bt.addActionListener(this);
p.add(txtserver);
p.add(txtport);
p.add(txtuser);
p.add(txtpwd);
p.add(bt);

frame=new JFrame("Configure mail");
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setVisible(true);

}
else if(e.getActionCommand().equals("Save and Close")){
saveConfigs();
frame.dispose();
}
}
class Th extends Thread{
String from;
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
String subject;
String message;
Th(String fromaddr,String[] toaddr,String[] bccaddr,String[] ccaddr,String subj,String mess){
from=fromaddr;
Tos=toaddr;
Bccs=bccaddr;
Ccs=ccaddr;
subject=subj;
message=mess;
lblstatus.setText("Sending the message");

}
public void run(){
sendEmail(from,Tos, Bccs,Ccs,subject, message);
email=null; //create object
lblstatus.setText("");
}
}
public void readConfigs(){
configs=new ArrayList<String>();
BufferedReader br=null;
try {
File f=new File("mailconfigs.con");
if(f.exists()){
FileReader fr=new FileReader(f);
br=new BufferedReader(fr);
String line="";
while((line=br.readLine())!=null){
configs.add(line);
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public void saveConfigs(){
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw = new FileWriter("mailconfigs.con");
bw=new BufferedWriter(fw);
bw.write(txtserver.getText());
bw.newLine();
bw.write(txtport.getText());
bw.newLine();
bw.write(txtuser.getText());
bw.newLine();
bw.write(encrypt(new String(txtpwd.getPassword())));



} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



public String encrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]+101);

return(new String(sb));
}

public String decrypt(String passw){

byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]-101);

return(new String(sb));
}

public void selectFile(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
listmodel.addElement(file.getPath());
       }
}

public void setEmailConfigs(String smtp,int port, String user, String password){
email = new  MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,decrypt(password));
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
}

public void sendEmail(String from, String[] Tos, String[] Bccs, String[] Ccs, String subject, String message){
configureMail();

if(email.getHostName().length()>0){
try {
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipients' (to) e-mail addresses
if(Tos!=null)
for(String Toadd:Tos)
email.addTo(Toadd);
//add recipients' (Bcc) e-mail addresses
if(Bccs!=null)
for(String Bccadd:Bccs)
email.addBcc(Bccadd);
//add recipients' (Cc) e-mail addresses
if(Ccs!=null)
for(String Ccadd:Ccs)
email.addCc(Ccadd);
//add file attachments
for(int i=0;i<listmodel.getSize();i++)
email.attach(new File(listmodel.get(i)));

//send the email
email.send();
}catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(this,"The email is not configured.");
}

}
}
public class EmailSender {
public static void main(String[] args){
new UI("E-Mail Sender");
}
}


compass app flashLight app

Thursday, October 24, 2013

Jar Pack

This is a simple Jar Pack program. You can use it to compress files or directories from your computers in a single jar file. It can be also used to extract an existing jar or zip file. The Jar Pack program has a very simple user interface which is divided in to two sections or parts. In the first section, there is a text box that you can enter the file or directory path to compress. Alternatively, you can click the Browse button to select a file from your computer. The file chooser allows you to select only file item. The selected file path will display in the text box. If you want to compress the directory that contains the file, you simply need to remove only the file name from the text box. You will press OK button to start compress the file or directory. The second section is similar to the first section except that it is for opening or extracting an existing jar or zip file.

The Jar Pack program uses the Apache Tika library to detect the mine type of file that the user selected to extract or open. Since this program is able to extract jar or zip file format, only a jar file or a zip file is allowed to extract. You will need to add the Tika library to the Java Build Path in Eclipse (Project->Properties->Java Build Path->Libraries->Add External Jars...) before you run the program.



In Java, creating jar and zip files are almost the same. The difference is that to create a jar file, you need to use the JarOutputStream class to write the content of the jar output file. Creating a zip file requires you to use the ZipOutputStream to write the content of the zip output file. Please read the Create Zip file page to read code explanation on compressing files and directories in zip file. Opening or extracting the jar file and the zip file are the sample so that you can read the code explanation about extracting a zip file on page Extract Zip.

Jar Pack program's source code

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.tika.Tika;

class JarUI extends JFrame{
JTextField txtFilePath;
JButton btFileBrowse;
JButton btFileOK;
JLabel lblFile;
JTextField txtArchivePath;
JButton btArchiveBrowse;
JButton btArchiveOK;
JLabel lblArchive;

JarUI(String title){
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,300);
setResizable(false);
Container cont=getContentPane();
cont.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel pPanel=new JPanel();
pPanel.setLayout(new BoxLayout(pPanel,BoxLayout.Y_AXIS));
JPanel filePanel=new JPanel(new GridLayout(2,2));
filePanel.setBorder(BorderFactory.createTitledBorder("Add to archive"));
txtFilePath=new JTextField(30);
btFileBrowse=new JButton(new AAction("Browse"));
btFileOK=new JButton(new AAction("OK"));
lblFile=new JLabel();
filePanel.add(txtFilePath);
filePanel.add(btFileBrowse);
filePanel.add(btFileOK);
filePanel.add(lblFile);

JPanel archivePanel=new JPanel(new GridLayout(2,2));
archivePanel.setBorder(BorderFactory.createTitledBorder("Extract jar or zip file"));
txtArchivePath=new JTextField(30);
btArchiveBrowse=new JButton(new AAction("Browse"));
btArchiveOK=new JButton(new AAction("OK"));
lblArchive=new JLabel();
archivePanel.add(txtArchivePath);
archivePanel.add(btArchiveBrowse);
archivePanel.add(btArchiveOK);
archivePanel.add(lblArchive);
pPanel.add(filePanel);
pPanel.add(archivePanel);
cont.add(pPanel);

setVisible(true);
}

class AAction extends AbstractAction{

AAction(String text){
super(text);
}
public void actionPerformed(ActionEvent e){

JButton bt=(JButton)e.getSource();
if(bt==btFileBrowse)
{
selectFile(txtFilePath);
}
else if(bt==btArchiveBrowse){
selectFile(txtArchivePath);
}
else if(bt==btFileOK){
final String path=txtFilePath.getText();
if(path.length()>0){
lblFile.setText("Please wait");
Thread t=new Thread(){
public void run(){
createJar(path);
lblFile.setText("Complete");
}
};
t.start();

}
else{
JOptionPane.showMessageDialog(null,"There is no file or folder name.");
}
}
else {
final String path=txtArchivePath.getText();
if(path.length()>0){
boolean b=isJarOrZip(path);
if(b){
lblArchive.setText("Please wait");
if(path.length()>0){
Thread t=new Thread(){
public void run(){
extractFile(txtArchivePath.getText(), System.getProperty("user.dir"));
lblArchive.setText("Complete");
}
};
t.start();

}
}
else{
JOptionPane.showMessageDialog(null,"It is not a jar or zip file.");
}
}
else{
JOptionPane.showMessageDialog(null,"There is no file name.");
}
}
}
}

//allow office word file selection for extracting
public void selectFile(JTextField path){

JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
    File file=chooser.getSelectedFile();    
    path.setText(file.getPath());
    }

     
}

public boolean isJarOrZip(String file){
boolean isJOZ=false;
Tika tika=new Tika();
try {
String mineType=tika.detect(new File(file));
if(mineType.endsWith("java-archive") || mineType.endsWith("zip"))
isJOZ=true;

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isJOZ;
}

public static void extractFile(String srcfile, String despath){
ZipFile zf=null;
    try {
zf=new ZipFile(srcfile); //create  a zip file object
if(zf.size()>0){ //read through the zip file
Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>) zf.entries();
while(entries.hasMoreElements()){
ZipEntry entry=entries.nextElement();
if(!entry.isDirectory() && !entry.getName().endsWith("/")){
//start extracting the files
extract(zf.getInputStream(entry),entry.getName(),despath);

}

}

}


} catch (IOException e) {

e.printStackTrace();

}finally{
if(zf!=null)
try {
zf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
    }
public static void extract(InputStream is, String fname, String storeDir){

FileOutputStream fos;
File fi=new File(storeDir+File.separator+fname); //output file
File fparent=new File(fi.getParent());
fparent.mkdirs();//create parent directories for output files

try {

fos=new FileOutputStream(fi);
int content=0;
while((content=is.read())!=-1){
fos.write(content);
}
is.close();
fos.close();
} catch (Exception e) {

e.printStackTrace();
}

}

//packaging file or directory
public void createJar(String src){
File f=new File(src);
File foutdir=new File(System.getProperty("user.dir")+"/jars");
if(!foutdir.exists()) foutdir.mkdir();
JarOutputStream zos=null;
try{
zos=new JarOutputStream(new FileOutputStream(foutdir.getPath()+"/jar"+System.currentTimeMillis()+".jar"));
if(f.exists()){
String fname=getName(f.getPath());
if(f.isFile()){
packFile(f.getPath(),fname,zos);
}
else{ //source is a directory
File[] files=f.listFiles();
for(File sf:files){
packDir(sf.getPath(),fname,zos);
}
}


}
else{
System.out.println("Soure not found!");
}
zos.close();

}catch(Exception e){e.printStackTrace();}

}
//get the name of source file or directory
public String getName(String srcpath){

String name="";
if(srcpath.endsWith(File.separator)){
name=srcpath.substring(0,srcpath.length()-1);
name=name.substring(name.lastIndexOf(File.separator)+1);
}
else
name=srcpath.substring(srcpath.lastIndexOf(File.separator)+1);

return name;
}
//packaging the directory and its contents
public void packDir(String srcpath, String dirname, JarOutputStream zos){
File fsrcdir=new File(srcpath);
String curDirName=getName(srcpath);
if(fsrcdir.isDirectory()){
try {
//add the blank folder to the jar file
//its previous path is maintained
curDirName=dirname+File.separator+curDirName;
zos.putNextEntry(new ZipEntry(curDirName+File.separator));
zos.closeEntry();
//read the contents of the directory and place them in the jar file
File[] files=fsrcdir.listFiles();
for(File f:files){
if(f.isDirectory()){ //process one directory download
packDir(f.getPath(),curDirName,zos);
}
else{//process the file
packFile(f.getPath(),curDirName,zos);
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
packFile(srcpath,dirname,zos);
}
}
//packaging  the file
public void packFile(String srcfile, String dirname,JarOutputStream zos){

String rpath=getName(srcfile);
//The rpath is a directory name that the file will be stored in
//It is the immediate parent directory of the file
try {
//placing one file entry
zos.putNextEntry(new ZipEntry(dirname+File.separator+rpath));
//create FileInputStream object to read content of the file
FileInputStream fis=new FileInputStream(srcfile);
int content=0;
while((content=fis.read())!=-1){
zos.write(content);
}
zos.closeEntry(); //closing one file entry
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}
public class JarCreator {

public static void main(String[] args) throws IOException{
new JarUI("Jar Pack");

}



}

compass app flashLight app

Sunday, October 6, 2013

Count words frequency

This is a simple program to count words frequency in an input file. In this program, there are two classes--Counter and CountWordsFrequency class. In the Counter class, two data structures are implemented--LinkedList and TreeMap. The Counter class has four methods. The first method, readWords() is called to read content from the input file and split the content in to words. Before adding these words to the LinkedList, the regular express is used to filter words by removing all symbols characters from the words. The Pattern class is used to define the pattern to be matched. The string pattern "\\W+" matches any symbol except underscore in a word. The Matcher class is able to remove the symbols from the words that match the string pattern. The second method is called countWords(). This method uses two loops to process all words and count the words frequency. The TreeMap is used to store the unique words and their frequencies. The words are stored automatically in TreeMap. The addToMap method is called by the countWords method to add words and frequencies to the TreeMap. The showResult method is invoked after the words and frequencies are added to the TreeMap to show the table of the words , frequencies, and the percentages.



java program to count words frequency



Its final method, processCounting combines the methods above in a single code block. This method will be invoked from the CounterWordsFreqency class to start analyzing the content of the input file and show the words frequency table. Below is the source code of the CountWordsFreqency program.

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Counter{
private String filename;
private LinkedList<String> keywordsList;
private TreeMap<String, Integer> freqMap;

Counter(String filename){
this.filename=filename;
freqMap=new TreeMap<String,Integer>();
keywordsList=new LinkedList<String>();
}

public void readWords(){
Pattern pattern=Pattern.compile("\\W+");
try {

FileReader fr=new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String strLine;
while((strLine=br.readLine())!=null){
//split a line by spaces so we get words
String[] words=strLine.split("[ ]+");
for(String word:words){
//remove all symbols except underscore
Matcher mat=pattern.matcher(word);
word=mat.replaceAll("");
//add words to the list
keywordsList.add(word.toLowerCase());
}
}

br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public void countWords(){
int count=1;
String word="";
for(int i=0;i<keywordsList.size();i++){
word=keywordsList.get(i);
for(int j=i+1;j<keywordsList.size();j++){
if(word.equals(keywordsList.get(j))){
count++; //increase the number of duplicate words
}
}
//add the word and its frequency to the TreeMap
addToMap(word,count);
//reset the count variable
count=1;
}

}

public void addToMap(String word, int count){
//place keyword and its frequency in TreeMap
if(!freqMap.containsKey(word) && word.length()>=1){
freqMap.put(word, count);
}

}


public void showResult(){
Set<String> keys=freqMap.keySet();
int numWord=keys.size();
Iterator<String> iterator=keys.iterator();
while(iterator.hasNext()){
String word=iterator.next();
int count=freqMap.get(word);
System.out.format("%-20s%-5d%-2s\n", word,count,100*count/numWord+"%");
}

}

public void processCounting(){
Thread backprocess=new Thread(){
public void run(){
readWords();
countWords();
showResult();
}
};
backprocess.start();
}



}

public class CountWordsFrequency{

public static void main(String[] args){
if(args.length>0){
Counter counter=new Counter(args[0]);
counter.processCounting();
}
else
System.out.println("No such file name");
}

}



compass app flashLight app