Pages

get our extension

Search program

Wednesday, 17 July 2013

Take a file as input, get the value from file and insert it in a ArrayList after inserting write all the values of list in other file...

sample: 
Input file: input.txt

class Employee
{
     private String name;
     public Integer age;
     protected Date dob;
     public Address addr;
     private Date doj;
     public  String designation;

}

output file: output.txt(Empty file)

InputFile.java

package com.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class InputFil
{
       public static void main(String[] args) throws IOException
       {        
           BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
           System.out.println("Enter File Name:");
           String fname=br.readLine();
        try
        {    
            @SuppressWarnings("unused")
            FileInputStream f=new FileInputStream(fname);
            System.out.println("*****************************************************");
             System.out.println("content of file are:");
             System.out.println("************************");
            FileReader file=new FileReader(fname);
            BufferedReader b=new BufferedReader(file);
            String s1=b.readLine();
            while(s1!=null)
            {
                    System.out.println(s1);
                    s1=b.readLine();        
            }
        }
        catch(FileNotFoundException e)
        {
            System.out.println("File not Found");
            return;
        }   
        System.out.println("*****************************************************");
        ArrayList<String>rows = new ArrayList<String>();
        try {
            System.out.println("*****************************************************");
            System.out.println("In Array List :");
            System.out.println("*******************");
            BufferedReader r = new BufferedReader(new FileReader(
                    fname));
            String line = null;
          
            while ((line = r.readLine()) != null)
            {
                String[] arr=line.split("\\s+");
              
                rows.add(line);
            }
            System.out.println(rows.toString());
        } catch (IOException e)
          {
            e.printStackTrace();
        }
            BufferedWriter writer=null;
            writer = new BufferedWriter(new FileWriter("output.txt"));
            //ObjectOutputStream out = new ObjectOutputStream((output));
            String listWord;
              
            for (int i = 0; i< rows.size(); i++)
            {
            listWord = rows.get(i);
            writer.write(listWord);
            writer.write("\n");
            }
            writer.close();   
        }
    }

output of program

Enter File Name:
input.txt
*****************************************************
content of file are:
************************
class Employee
{
     private String name;
     public Integer age;
     protected Date dob;
     public Address addr;
     private Date doj;
     public  String designation;

}
*****************************************************
*****************************************************
In Array List :
*******************
[class Employee, {,      private String name;,      public Integer age;,      protected Date dob;,      public Address addr;,      private Date doj;,      public  String designation;, , }]



open output.txt (we can see all data in input.txt now available in output.txt)

class Employee
{
     private String name;
     public Integer age;
     protected Date dob;
     public Address addr;
     private Date doj;
     public  String designation;

}

Java Program To Print Consecutive characters and the number of times it occurs in ascending order of number of occurrences

Sample 
-----------
 input : “I saw a cd player and a modem in ccd”

     output :  de-->  1 
                  cd --> 2 
                  I saw a player and a mom in c

ContiAlpha.java

package com.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;

public class ContiAlpha
{
    public static void main(String[] args) throws IOException
    {
      try
      {
        HashMap<String, Integer> map= new HashMap<String, Integer>();
        String s1="I saw a cd  ghplayer and a modem degh in ccd";
        s1=s1.toLowerCase();
        for(int i=0;i<(s1.length()-1);i++)
        {
            if(s1.charAt(i+1)-s1.charAt(i)==1)
            {
                String word=s1.charAt(i)+""+s1.charAt(i+1);
       
                if(map.containsKey(word))
                {
                    int value=map.get(word);
                    map.put(word,++value);
                } 
                    else
                    {
                        map.put(word, 1);
                    }
            }               
        }  
        ArrayList<ContiSortByValue> list=new ArrayList<ContiSortByValue>();
             Set<String> keySet=map.keySet();
             String s2=s1;
             for(String k : keySet)
             {
                  s2=s2.replace(k, "");
                 int value=map.get(k);
                 list.add(new ContiSortByValue(k, value));             
             }
             System.out.println(s2);
             Collections.sort(list);
             for(ContiSortByValue sort : list)
             {
                 System.out.println(sort);
             }
      }   
      catch (Exception e)
      {
            e.printStackTrace();
      }           
    }

}

ContiSortByValue.java 

package com.test;
public class ContiSortByValue implements Comparable<ContiSortByValue>
{
    private String key;
    private Integer value;
    public ContiSortByValue()
    {
        // TODO Auto-generated constructor stub
    }
       public ContiSortByValue(String key, Integer value)
      {
        super();
        this.key = key;
        this.value = value;
      }
    @Override
    public int compareTo(ContiSortByValue obj)
   {    
        return this.value - obj.value;
    }
    @Override
    public String toString()
    {
        return key + "-->" + value;
    }

}
output:

de-->1
cd-->2
i saw a  player and a mom in c 

Java Program toFind duplicates and unique set

Example Input :
  an array of String contains :String[] str = new String[] {"alok", "dhoni", "manish", "rajiv", "alok", "rajiv"}

output : 
 unique items: [manish, dhoni]
Duplicate items : [alok, rajiv]


 SetExampl.java 
package com.alok.Uniqueduplicate;
import java.util.HashSet;
import java.util.Set;

public class SetExample
{
    public static void main(String[] args)
    {
    String[] str = new String[] {"alok", "dhoni", "manish", "rajiv", "alok", "rajiv"};
    Set<String> duplicateSet = new HashSet<String>();
    Set<String> uniqueSet = new HashSet<String>();
        for(int  i = 0; i < str.length ; i++ )
        {
            if(!uniqueSet.add(str[i]))
            {
                duplicateSet.add(str[i]);
            }
        }
        uniqueSet.removeAll(duplicateSet);
        System.out.println("unique items: "+uniqueSet);
        System.out.println("Duplicate items : "+ duplicateSet);
    }

}

output : 
unique items: [manish, dhoni]
Duplicate items : [alok, rajiv]

PROGRAM TO SHOW THE USE OF HasSet, Iterator AND for Loop

HashSet_Example.java

package com.alok;

import java.io.IOException;
import java.util.*;

public class HashSet_Example
{
public static void main(String[] args)throws IOException
{
String str[]={"alok","manish","Pravin","rajiv","pratyush"};
//create a HashSet to store above string
HashSet<String> hs= new HashSet<String>();
//Storing elements to HashSet
for(int i=0;i<str.length;i++)
{
hs.add(str[i]);
}
System.out.println(hs);
//add an iterator to HashSet
Iterator<String> it= hs.iterator();
//Displaying elements using iterator
System.out.println("Retrieve Elements from HashSet using Iterator..");
while(it.hasNext())
{
String s=it.next();
System.out.println(s);
}
//Displaying Elements using For-each loop...
System.out.println("\nRetrieve Elements using for loop....");
for(String var:hs)
{
System.out.println(var);
}
}


}

OUTPUT

[manish, alok, Pravin, pratyush, rajiv]
Retrieve Elements from HashSet using Iterator..
manish
alok
Pravin
pratyush
rajiv

Retrieve Elements using for loop....
manish
alok
Pravin
pratyush
rajiv

Sunday, 23 June 2013

Write Your First String Program

First create a POJO class
Right Click on
SRC ( inside application 1)à newà class
Write any package name like I’m writing com.alok and give class name like Book then click finish

package com.alok;

public class Book
{
      private String title;
      private String author;
      public Book()
      {
            System.out.println("Book()");
      }
      public String getTitle() {
            System.out.println("getTitle");
            return title;
      }
      public void setTitle(String title) {
            System.out.println("set title");
            this.title = title;
      }
      public String getAuthor() {
            System.out.println("getAuthor");
            return author;
      }
      public void setAuthor(String author) {
            System.out.println("set Author");
            this.author = author;
      }
     
}

Inside config.xml register this POJO class with a unique bean id

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="b1" class="com.alok.Book">
      <property name="title" value="java made easy"></property>
      <property name="author" value="prince"></property>

</bean>

</beans>




 à b1 is pointing to a object which is already created then we are calling setTitle and setAuthor 

à inside config.xml, for every bean tag, object is created

à All Setter method is calling before delimiter itself

Now Develop a Client Program

src-->com.alok-->new--> class

BookClient.java

package com.alok;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookClient {
public static void main(String[] args) {
BeanFactory fac=new ClassPathXmlApplicationContext(new String[]{"config.xml"});
System.out.println("----111-----");
Book b1=(Book)fac.getBean("b1");
System.out.println("----222-----");
System.out.println(b1.getTitle());
System.out.println(b1.getAuthor());
}

}
à  While creating beanFactory object inside config.xml, corresponding setter and getter method is calling

try to understand output
output:-
Book()
set title
set Author
Book()
set title
set Author
----111-----
----222-----
getTitle
java made easy
getAuthor
prince

First Step in STC

When STC is opened then click on
 FileànewàSpring Project
Give any name, for example I’m giving application 1
Now Right click on
 application 1à propertiesà Java Build Path
Click on adds external JARs and first adds all jar files inside spring-framework-4.0.0.M1/libs
Again click on adds external JARs and add all jar files inside commons-logging-1.1.3

Right Click on  src (inside application 1)ànewàSpring bean configuration file
Give any name like I’m giving config.xml
Contents already exist inside config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>


Now write your first spring program

Monday, 10 June 2013

Getting Started with Spring

(1) First Download Spring FrameWork
-----> latest version is 4.0

click below link to download spring Framework 4.0
http://www.springsource.org/download/community

download only
spring-framework-4.0.0.M1-dist.zip(sha1)47.6 MB
Three inside this Zip folder.
      ---1. docs
      ---2. libs --------> there are several jar files.
      ---3. schema

----------> The whole spring framework is developed in JAVA


(2). Second Download Commons-logging- 1.1.3
   ----> these jar files are using for internally logging purpose

click below link to download Commons-logging- 1.1.3

from here download commons-logging-1.1.3-bin.zip

(3).  Last Download Spring Tool Suite
        
click below link to download Spring Tool Suite

from here download depend on your computer configuration(32bit or 64 bit)





After download Spring Tool Suite-3.2.0
--->click on STC icon. now you are ready to write your first spring program
     (Very similar to Eclipse)

(All download links are from http://www.springsource.org   and all right reserved@Spring by Pivotal )