skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Wednesday, October 24, 2012

Alphanumeric String Sorting using Java

Posted by Raju Gupta at 6:30 PM – 0 comments
 

Alphanumeric is a combination of alphabetic and numeric characters (sometimes shortened to alphameric).

In computing, the alphanumeric Strings can be seen very common to represent various codes etc. Sorting the alphanumeric strings can sometimes be a trouble by using regular sort techniques.

import java.util.Arrays;
import java.util.Comparator;
 
public class AlphanumericSorting implements Comparator {
    /**
     * The compare method that compares the alphanumeric strings
     */
    public int compare(Object firstObjToCompare, Object secondObjToCompare) {
        String firstString = firstObjToCompare.toString();
        String secondString = secondObjToCompare.toString();
 
        if (secondString == null || firstString == null) {
            return 0;
        }
 
        int lengthFirstStr = firstString.length();
        int lengthSecondStr = secondString.length();
 
        int index1 = 0;
        int index2 = 0;
 
        while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
            char ch1 = firstString.charAt(index1);
            char ch2 = secondString.charAt(index2);
 
            char[] space1 = new char[lengthFirstStr];
            char[] space2 = new char[lengthSecondStr];
 
            int loc1 = 0;
            int loc2 = 0;
 
            do {
                space1[loc1++] = ch1;
                index1++;
 
                if (index1 < lengthFirstStr) {
                    ch1 = firstString.charAt(index1);
                } else {
                    break;
                }
            } while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
 
            do {
                space2[loc2++] = ch2;
                index2++;
 
                if (index2 < lengthSecondStr) {
                    ch2 = secondString.charAt(index2);
                } else {
                    break;
                }
            } while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
 
            String str1 = new String(space1);
            String str2 = new String(space2);
 
            int result;
 
            if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
                Integer firstNumberToCompare = new Integer(Integer
                        .parseInt(str1.trim()));
                Integer secondNumberToCompare = new Integer(Integer
                        .parseInt(str2.trim()));
                result = firstNumberToCompare.compareTo(secondNumberToCompare);
            } else {
                result = str1.compareTo(str2);
            }
 
            if (result != 0) {
                return result;
            }
        }
        return lengthFirstStr - lengthSecondStr;
    }
 
    /**
     * Testing the alphanumeric sorting
     */
    public static void main(String[] args) {
        String[] alphaNumericStringArray = new String[] { "NUM10071",
                "NUM9999", "9997", "9998", "9996", "9996F" };
 
        /*
         * Arrays.sort method can take an unsorted array and a comparator
         * to give a final sorted array.
         *
         * The sorting is done according to the comparator that we have
         * provided.
         */
        Arrays.sort(alphaNumericStringArray, new AlphanumericSorting());
 
        for (int i = 0; i < alphaNumericStringArray.length; i++) {
            System.out.println(alphaNumericStringArray[i]);
        }
 
    }
 
}

[ Read More ]
Read more...

Calculating Age using Java

Posted by Raju Gupta at 12:30 PM – 0 comments
 
To check the age from the given year.

import java.util.GregorianCalendar;
import java.util.Calendar;

public class AgeCalculation {

 /**
  * Month Representations
  */
 static final int JAN = 0;
 static final int FEB = 1;
 static final int MAR = 2;
 static final int APR = 3;
 static final int MAY = 4;
 static final int JUN = 5;
 static final int JUL = 6;
 static final int AUG = 7;
 static final int SEP = 8;
 static final int OCT = 9;
 static final int NOV = 10;
 static final int DEC = 11;

 public static void main(String[] args) {
  System.out.println("Born In 1982-JUL-11. Current Age: "
    + calculateMyAge(1982, JUL, 11));
  System.out.println("Born In 1957-DEC-09. Current Age: "
    + calculateMyAge(1957, DEC, 9));
 }

 /**
  *
  * @param year --> Birth Year
  * @param month --> Birth Month
  * @param day --> Birth Day
  * @return --> Calculated Age
  */
 private static int calculateMyAge(int year, int month, int day) {
  Calendar birthCal = new GregorianCalendar(year, month, day);

  Calendar nowCal = new GregorianCalendar();

  int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

  boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
    .get(Calendar.MONTH);

  boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) == nowCal
    .get(Calendar.MONTH)
    && birthCal.get(Calendar.DAY_OF_MONTH) > nowCal
    .get(Calendar.DAY_OF_MONTH);

    if (isMonthGreater || isMonthSameButDayGreater) {
     age=age-1;
    }
    return age;
 }

}


[ Read More ]
Read more...

Unicast Messaging in Java

Posted by Raju Gupta at 7:00 AM – 0 comments
 
Unicast messaging is used for all network processes in which a private or unique resource is requested.

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.JFrame;

public class Unicast extends JFrame implements ActionListener{
 Label entermsgl,receivedmsgl,sentmsgl,toportl;
 TextField entermsg,toport;
 TextArea receivedmsg,sentmsg;
 Button send,exit;
 int myport;
 DatagramSocket ds;
 DatagramPacket dp;
 Unicast(){
  new InputDialog(this);
 }
 public void initialise(){
  setTitle("Unicast --Port:"+myport);
  setVisible(true);
  setSize(600,400);
  entermsgl=new Label("Enter Message:");
  receivedmsgl=new Label("Received Messages:");
  sentmsgl=new Label("Sent Messages:");
  toportl=new Label("To");
  toport=new TextField();
  entermsg=new TextField();
  receivedmsg=new TextArea();
  sentmsg=new TextArea();
  send=new Button("Send");
  exit=new Button("Exit");
  setLayout(null);
  add(entermsgl);
  entermsgl.setBounds(25,25,100,25);
  add(receivedmsgl);
  receivedmsgl.setBounds(25,70,150,25);
  add(sentmsgl);
  sentmsgl.setBounds(25,185,150,25);
  add(toportl);
  toportl.setBounds(350,25,25,25);
  add(toport);
  toport.setBounds(380,25,70,25);
  add(entermsg);
  entermsg.setBounds(130,25,200,25);
  add(receivedmsg);
  receivedmsg.setBounds(180,70,370,100);
  add(sentmsg);
  sentmsg.setBounds(180,185,370,100);
  add(send);
  send.setBounds(470,25,100,25);
  add(exit);
  exit.setBounds(250,300,100,25);
  try{
   ds=new DatagramSocket(myport);
  }catch(Exception e){
   System.out.println(e);
  }
  send.addActionListener(this);
  exit.addActionListener(this);
  new Receive();
 }
 class Receive extends Thread{
  Receive(){
   start();
  }
  public void run(){
   while(true){
    try{
     byte b[]=new byte[100];
     dp=new DatagramPacket(b,b.length);
     ds.receive(dp);
     receivedmsg.append("From "+dp.getPort()+": "+new String(dp.getData(),0,dp.getLength())+"n");
    }catch(Exception e){
     
    }
   }
   
  }
 }
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==send){
   byte b[]=entermsg.getText().getBytes();
   try{
    int port=Integer.parseInt(toport.getText());
    if(port<1024 || port>65536){
      toport.setText("");
      return;
    }
    dp=new DatagramPacket(b,b.length,InetAddress.getLocalHost(),port);
    ds.send(dp);
    sentmsg.append("To "+port+": "+entermsg.getText()+"n");
   }catch(NumberFormatException nfe){
    toport.setText("");
   }catch(Exception e){
    
   }
  }
  else{
   System.exit(0);
  }
 }
 public static void main(String args[]){
  new Unicast();
 }

}


class InputDialog extends Dialog implements ActionListener{
 Button ok=new Button("Ok");
 Button cancel=new Button("Cancel");
 TextField tf=new TextField();
 Label l=new Label("Enter the port number:");
 Unicast parent;
 InputDialog(Unicast f){
  super(f,"Unicast - Port number");
  parent=f;
  setVisible(true);
  setSize(400,200);
  setLayout(null);
  add(l);
  l.setBounds(25,50,200,25);
  add(tf);
  tf.setBounds(225,50,100,25);
  add(ok);
  ok.setBounds(100,100,100,25);
  add(cancel);
  cancel.setBounds(220,100,100,25);
  ok.addActionListener(this);
  cancel.addActionListener(this);
 } 
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==ok){
   try{
    int n=Integer.parseInt(tf.getText());
    if(n>1023 && n<65536){
     parent.myport=n;
     parent.initialise();
     this.dispose();
    }
    else{
     tf.setText("");
     tf.requestFocus();
    }
   }catch(NumberFormatException nfe){
    tf.setText("");
    tf.requestFocus();
   }
  }
  else if(ae.getSource()==cancel){
   System.exit(0);
  }
  
 }
}

[ Read More ]
Read more...

Chat Client and Chat Server

Posted by Raju Gupta at 2:26 AM – 0 comments
 
Communication between the clients from Server

//Chat Server:-

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatServer extends Frame implements ActionListener{
 Label listOfClients;
 List clientName;
 Button exit;
 Panel p1,p2;
 ServerSocket ss;
 Clients clients[];
 int n;
 boolean sendOk=true;
 boolean update=false;

 ChatServer(){
  super("ChatServer");
  setSize(400,300);
  setVisible(true);
  clientName=new List();
  listOfClients=new Label("List of Clients");
  exit=new Button("Exit");
  p1=new Panel();
  p2=new Panel();
  p1.setLayout(new FlowLayout());
  p2.setLayout(new FlowLayout());
  setLayout(new GridLayout(2,1));
  add(p1);
  add(p2);
  p1.add(listOfClients);
  p1.add(clientName);
  p2.add(exit);
  exit.addActionListener(this);
  try{
   ss=new ServerSocket(2500);
  }catch(Exception e){
  }
  clients=new Clients[50];
  n=0;
  new CheckNewClients().start();
  new UpdateClients().start();
  
 }
 public void actionPerformed(ActionEvent ae){
  System.exit(0);
 }
 public static void main(String args[]){
  new ChatServer();
 }
 class Clients extends Thread{
  Socket s;
  BufferedReader br;
  PrintWriter pw;
  String name="Client ";
  int i;
  boolean alive;
  public void run(){
   try{
    while(true){
     String temp=br.readLine();
     if(temp.equals("shutdown")){
      for(int x=0;x<clientName.getItemCount();x++)
       if(clientName.getItem(x).equals(name)){
        clientName.remove(x);
        break;
       }
      alive=false;
      update=true;
      break;
     }
     else if(temp.equals("msg")){
      String client=br.readLine(); 
      String msg=br.readLine();
      int x;
      for(x=0;x<n;x++)
       if(clients[x].name.equals(client))
        break;
      while(!sendOk);
      sendOk=false;
      clients[x].pw.println("msg");
      clients[x].pw.println(name+" : "+msg);
      sendOk=true;
     }
    }
   }catch(Exception e){ 
    for(int x=0;x<clientName.getItemCount();x++)
     if(clientName.getItem(x).equals(name)){
      clientName.remove(x);
      break;
     }
    alive=false;
    update=true;
   }
  }
 }
 class CheckNewClients extends Thread{
  public void run(){
   while(true){
    clients[n]=new Clients();
    try{
     clients[n].s=ss.accept(); 
     clients[n].br=new BufferedReader(new InputStreamReader(clients[n].s.getInputStream()));
     clients[n].pw=new PrintWriter(clients[n].s.getOutputStream(),true);
     clients[n].i=n;
     clients[n].name+=n;
     clients[n].alive=true;
     clientName.add(clients[n].name);
     clients[n].pw.println(clients[n].name);
     clients[n].start(); 
     update=true;
    }catch(Exception e){
     System.out.println(e);
    }
    n++;
   }
  }
 }
 class UpdateClients extends Thread{
  public void run(){
   while(true){
    while(!update);
    for(int i=0;i<n;i++){
     int count=clientName.getItemCount();
     if(!clients[i].alive)
      continue;
     try{
      while(!sendOk);
      sendOk=false;
      clients[i].pw.println("update");
      clients[i].pw.println(count-1);
      for(int x=0;x<count;x++)
       if(!clientName.getItem(x).equals(clients[i].name))
        clients[i].pw.println(clientName.getItem(x));
      sendOk=true;
     }catch(Exception e){
      System.out.println(e);
     }
    }
    update=false;
   }
  }
 }
}


//Chat Client:-

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient extends Frame implements ActionListener{
 Label enterMessage,to,receivedMessages,sentMessages;
 TextField enterMessaget;
 TextArea receivedMessagest,sentMessagest;
 Button send,exit;
 Choice clientName;
 Panel p1,p2,p3,p4;
 Socket s;
 PrintWriter pw;
 BufferedReader br;

 ChatClient(){
  super("ChatClient");
  setVisible(true);
  setSize(500,300);
  enterMessage=new Label("Enter Message");
  to=new Label("To");
  receivedMessages=new Label("Received Messages");
  sentMessages=new Label("Sent Messages");
  enterMessaget=new TextField();
  receivedMessagest=new TextArea("",20,5,TextArea.SCROLLBARS_VERTICAL_ONLY);
  sentMessagest=new TextArea();
  clientName=new Choice();
  send=new Button("Send");
  exit=new Button("Exit");
  p1=new Panel();
  p2=new Panel();
  p3=new Panel();
  p4=new Panel();
  setLayout(new GridLayout(4,1));
  p1.setLayout(null);
  p2.setLayout(new GridLayout(1,2));
  p3.setLayout(new GridLayout(1,2));
  p4.setLayout(new FlowLayout());
  p1.add(enterMessage);
  enterMessage.setBounds(10,10,100,25);
  p1.add(enterMessaget);
  enterMessaget.setBounds(110,10,100,25);
  p1.add(to);
  to.setBounds(220,10,30,25);
  p1.add(clientName);
  clientName.setBounds(260,10,100,25);
  p1.add(send);
  send.setBounds(370,10,100,25);
  p2.add(receivedMessages);
  p2.add(receivedMessagest);
  p3.add(sentMessages);
  p3.add(sentMessagest);
  p4.add(exit);
  add(p1);
  add(p2);
  add(p3);
  add(p4);
  exit.addActionListener(this); 
  send.addActionListener(this);
  try{
   s=new Socket("localhost",2500);
   br=new BufferedReader(new InputStreamReader(s.getInputStream()));
   pw=new PrintWriter(s.getOutputStream(),true);
   setTitle(br.readLine());
  }catch(Exception e){
   System.out.println("Exception: Problem establishing connectionn"+e);
  }
  new ReceiveMsg().start();
 }
 public static void main(String args[]){
  new ChatClient();
 }
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==send){
   try{
    pw.println("msg");
    String client=clientName.getSelectedItem();
    String msg=enterMessaget.getText();
    pw.println(client);
    pw.println(msg);
    sentMessagest.append(client+" : "+msg+"n");
   }catch(Exception e){
   }
   
  }
  else if(ae.getSource()==exit){
   try{
    pw.println("shutdown");
   }catch(Exception e){
   }
   System.exit(0);
  }
 }
 class ReceiveMsg extends Thread{
  public void run(){
   while(true){
    try{
     String temp=br.readLine();
     if(temp.equals("update")){
      receiveUpdate();     
     }
     else if(temp.equals("msg")){
      receiveMsg();
     }
    }catch(Exception e){
    }
   }    
  }
  public void receiveMsg(){
   try{
    receivedMessagest.append(br.readLine()+"n");
   }catch(Exception e){
   }
  }
  public void receiveUpdate(){
   try{
    int n=Integer.parseInt(br.readLine());
    clientName.removeAll();
    for(int i=0;i<n;i++)
     clientName.add(br.readLine());      
   }catch(Exception e){
   }
  }
 }
 class sendUpdate extends Thread{
  public void run(){
   while(true){
    pw.println("alive");
    try{
     sleep(10000);
    }catch(Exception e){
    }
   }
  }
 }
}

[ Read More ]
Read more...
Tuesday, October 23, 2012

MultiCast Messaging in Java

Posted by Raju Gupta at 9:30 PM – 0 comments
 
Sending the file or message to a set of clients or group of clients

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.JFrame;

public class Multicast extends JFrame implements ActionListener,Runnable{
 Label entermsgl,receivedmsgl,sentmsgl;
 TextField entermsg;
 TextArea receivedmsg,sentmsg;
 Button Multicast,exit;
 int myport;
 MulticastSocket ms_send,ms_receive;
 DatagramPacket dp;
 InetAddress address;
 Thread t;
 Multicast(){
  initialise();
 }
 public void initialise(){
  setTitle("Multicast ");
  setVisible(true);
  setSize(600,400);
  entermsgl=new Label("Enter Message:");
  receivedmsgl=new Label("Received Messages:");
  sentmsgl=new Label("Sent Messages:");
  entermsg=new TextField();
  receivedmsg=new TextArea();
  sentmsg=new TextArea();
  Multicast=new Button("Multicast");
  exit=new Button("Exit");
  setLayout(null);
  add(entermsgl);
  entermsgl.setBounds(25,25,100,25);
  add(receivedmsgl);
  receivedmsgl.setBounds(25,70,150,25);
  add(sentmsgl);
  sentmsgl.setBounds(25,185,150,25);
  add(entermsg);
  entermsg.setBounds(130,25,200,25);
  add(receivedmsg);
  receivedmsg.setBounds(180,70,370,100);
  add(sentmsg);
  sentmsg.setBounds(180,185,370,100);
  add(Multicast);
  Multicast.setBounds(470,25,100,25);
  add(exit);
  exit.setBounds(250,300,100,25);
  try{
   address=InetAddress.getByName("230.150.150.15");
   ms_send=new MulticastSocket();
   ms_receive=new MulticastSocket(2001);
   ms_receive.joinGroup(address);
  }catch(Exception e){
   System.out.println(e);
  }
  Multicast.addActionListener(this);
  exit.addActionListener(this);
  t=new Thread(this);
  t.start();
 }
 //class Receive extends Thread{
 // Receive(){
  // start();
  //}
  public void run(){
   while(true){
    System.out.println("1");
    try{
     DatagramPacket dp1;
     byte b[]=new byte[100];
     System.out.println("2");
     dp1=new DatagramPacket(b,b.length);
     ms_receive.receive(dp1);
     System.out.println("3");
     receivedmsg.append("From "+dp1.getAddress()+" "+dp1.getPort()+": "+new String(dp1.getData(),0,dp1.getLength())+"\n");
     repaint();
    }catch(Exception e){
     System.out.println(e);
    }
   }
   
  }
 //}
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==Multicast){
   byte b[]=entermsg.getText().getBytes();
   try{
    dp=new DatagramPacket(b,b.length,address,2001);
    ms_send.send(dp,(byte)1);
    sentmsg.append(ms_send.getLocalAddress()+" port:"+ms_send.getLocalPort()+": "+entermsg.getText()+"\n");
   }catch(NumberFormatException nfe){
   }catch(Exception e){
    System.out.println(e);
   }
  }
  else{
   System.exit(0);
  }
 }
 public static void main(String args[]){
  new Multicast();
 }

}


[ Read More ]
Read more...

File checksum in Java

Posted by Raju Gupta at 12:00 PM – 0 comments
 
If want to check two files and calculate their hashcode to make sure files are different or same. This function will caluclate the file checksum to compare two files. It will take file as an input.

//To generate a file checksum value with "SHA-1" mechanism 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "c:\INSTLOG.TXT";
 
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
     sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}

[ Read More ]
Read more...

conversion of HTML data to TEXT

Posted by Raju Gupta at 5:30 AM – 0 comments
 
The contents from HTML page is extracted and diplayed in text format. The HTML page is given as input where the java code removes the HTML tags and the text is extracted.

import java.io.File;
import java.io.FileInputStream;

import java.io.Reader;
import java.io.StringReader;

import java.io.IOException;

/**
 * Convert text/html into text/plain
 */

public class HTML2Text
{
 boolean body_found = false;
 boolean in_body = false;
 boolean center = false;
 boolean pre = false;
 String href = "";

 public String convert(String source) throws Exception
 {
  StringBuffer result = new StringBuffer();
  StringBuffer result2 = new StringBuffer();
  StringReader input = new StringReader(source);

  try
  {
   String text = null;
   int c = input.read();

   while (c != -1) // Convert until EOF
   {
    text = "";
    if (c == '<') // It's a tag!!
    {
     String CurrentTag = getTag(input); // Get the rest of the tag
     text = convertTag(CurrentTag);
    }
    else if (c == '&')
    {
     String specialchar = getSpecial(input);
     if (specialchar.equals("lt;") || specialchar.equals("#60"))
      text = "<";
     else if (specialchar.equals("gt;") || specialchar.equals("#62"))
      text = ">";
     else if (specialchar.equals("amp;") || specialchar.equals("#38"))
      text = "&";
     else if (specialchar.equals("nbsp;"))
      text = " ";
     else if (specialchar.equals("quot;") || specialchar.equals("#34"))
      text = """;
      else if (specialchar.equals("copy;") || specialchar.equals("#169"))
       text = "[Copyright]";
      else if (specialchar.equals("reg;") || specialchar.equals("#174"))
       text = "[Registered]";
      else if (specialchar.equals("trade;") || specialchar.equals("#153"))
       text = "[Trademark]";
      else
       text = "&" + specialchar;
    }
    else if (!pre && Character.isWhitespace((char)c))
    {
     StringBuffer s = in_body ? result : result2;
     if (s.length() > 0 && Character.isWhitespace(s.charAt(s.length()-1)))
      text = "";
     else text = " ";
    }
    else
    {
     text = "" + (char)c;
    }

    StringBuffer s = in_body ? result : result2;
    s.append(text);

    c = input.read();
   }
  }
  catch (Exception e)
  {
   input.close();
   throw e;
  }

  StringBuffer s = body_found ? result : result2;
  return s.toString().trim();
 }

 String getTag(Reader r) throws IOException
 {
  StringBuffer result = new StringBuffer();
  int level = 1;

  result.append('<');
  while (level > 0)
  {
   int c = r.read();
   if (c == -1) break; // EOF
   result.append((char)c);
   if (c == '<') level++; else if (c == '>') level--;
  }

  return result.toString();
 }

 String getSpecial(Reader r) throws IOException
 {
  StringBuffer result = new StringBuffer();
  r.mark(1);//Mark the present position in the stream
  int c = r.read();

  while (Character.isLetter((char)c))
  {
   result.append((char)c);
   r.mark(1);
   c = r.read();
  }

  if (c == ';') result.append(';');
  else r.reset();

  return result.toString();
 }

 boolean isTag(String s1, String s2)
 {
  s1 = s1.toLowerCase();
  String t1 = "<" + s2.toLowerCase() + ">";
  String t2 = "<" + s2.toLowerCase() + " ";

  return s1.startsWith(t1) || s1.startsWith(t2);
 }

 String convertTag(String t) throws IOException
 {
  String result = "";

  if (isTag(t,"body"))
  { in_body = true; body_found = true; }
  else if (isTag(t,"/body"))
  { in_body = false; result = "
  "; }
  else if (isTag(t,"center"))
  { result = "
  "; center = true; }
  else if (isTag(t,"/center"))
  { result = "
  "; center = false; }
  else if (isTag(t,"pre"))
  { result = "
  "; pre = true; }
  else if (isTag(t,"/pre"))
  { result = "
  "; pre = false; }
  else if (isTag(t,"p"))
   result = "

   ";
   else if (isTag(t,"br"))
    result = "
    ";
    else if (isTag(t,"h1") || isTag(t,"h2") || 
      isTag(t,"h3") ||isTag(t,"h4") || isTag(t,"h5") || isTag(t,"h6") || isTag(t,"h7"))
     result = "
     ";
     else if (isTag(t,"/h1") || isTag(t,"/h2") || 
       isTag(t,"/h3") ||isTag(t,"/h4") || isTag(t,"/h5") || isTag(t,"/h6") || isTag(t,"/h7"))
      result = "
      ";
      else if (isTag(t,"/dl"))
       result = "
       ";
       else if (isTag(t,"dd"))
        result = "
        * ";
        else if (isTag(t,"dt"))
         result = "      ";
        else if (isTag(t,"li"))
         result = "
         * ";
         else if (isTag(t,"/ul"))
          result = "
          ";
          else if (isTag(t,"/ol"))
           result = "
           ";
           else if (isTag(t,"hr"))
            result = "_________________________________________

            ";
            else if (isTag(t,"table"))
             result = "
             ";
             else if (isTag(t,"/table"))
              result = "
              ";
              else if (isTag(t,"form"))
               result = "
               ";
               else if (isTag(t,"/form"))
                result = "
                ";
                else if (isTag(t,"b"))
                 result = "*";
                else if (isTag(t,"/b"))
                 result = "*";
                else if (isTag(t,"i"))
                 result = """;
                 else if (isTag(t,"/i"))
                  result = """;
                  else if (isTag(t,"img"))
                  {
                   int idx = t.indexOf("alt="");
                     if (idx != -1)
                     {
                      idx += 5;
                      int idx2 = t.indexOf(""",idx);
                        result = t.substring(idx,idx2);
                     }
                  }
                  else if (isTag(t,"a"))
                  {
                   int idx = t.indexOf("href="");
                     if (idx != -1)
                     {
                      idx += 6;
                      int idx2 = t.indexOf(""",idx);
                        href = t.substring(idx,idx2);
                     }
                     else
                     {
                      href = "";
                     }
                  }
                  else if (isTag(t,"/a"))
                  {
                   if (href.length() > 0)
                   {
                    result = " [ " + href + " ]";
                    href = "";
                   }
                  }

  return result;
  }

  public static void main(String argv[]) throws Exception
  {
   FileInputStream fis = null;
   String s = null;

   try
   {
    File file;
    if (argv[0] != null) file = new File(argv[0]);
    else file = new File("html_test_file.html");
    fis = new FileInputStream(file);
    byte buf[] = new byte[fis.available()];
    //bytes that can be read from this file input stream without blocking

    fis.read(buf);
    fis.close();
    fis = null;
    s = new String(buf);
    HTML2Text h = new HTML2Text();
    System.out.println(h.convert(s));
   }
   catch (Exception e)
   {
    if (fis != null) fis.close();
    throw e;
   }
  }
  }

[ Read More ]
Read more...
Newer Posts Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Comparison of Two Variable using If | JAVA Program
    Here is a Java Program to show Comparison Operation on the two variable using If Control Structure class IfComparison { public static vo...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Java Utility program
    The java utility program is used to Read from a properties file,make DB connections,read from a file and Write into a file. import java.s...
  • CheckSum Login in java
    A Checksum is used for error checking while transferring data from server to server or client to server. Data is flown across networks in t...
  • Alphanumeric String Sorting using Java
    Alphanumeric is a combination of alphabetic and numeric characters (sometimes shortened to alphameric). In computing, the alphanume...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • How to swap two numbers using only two variables in Java
     Here's a program to swap two numbers using only two variables with explanation using Java Programming language.
  • Define a class to represent a length measured in meters, centimeters, and millimeters | Java Program
    Define a class, mcmLength, to represent a length measured in meters, centimeters, and millimeters, each stored as integers. Include methods...
  • Sorting a List in ascending order
    This code snippet sorts a list of objects based on the value of a field of those objects import java.util.ArrayList; import java.util...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger