Monday, 30 December 2013

Breaking Input into Tokens Java


Scanning

Objects of type scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.

Breaking Input into Tokens

By default, a scanner uses white space to separate tokens.

First  we have create .txt file or we can use our existing .txt file.  


A program that reads the individual words in .txtand prints them out, one per line.



import java.io.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ScanXan {
   
    public static void main(String[] args) {
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("D:\\doc.txt")));

            while (s.hasNext()) {
                System.out.println(s.next());
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ScanXan.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
   
}

Output -



Monday, 23 December 2013

File Compress and decompress in java


File Compress and decompress java program-

For example first we have to create folder and copy file into the folder which one we want to compress.

Open net beans create new project and write below code for compress your file.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.DeflaterOutputStream;
public class CompressFile {
public static void main(String[] args) {
try{
FileInputStream fin=new FileInputStream("D:\\Compress\\introduction.pdf");
FileOutputStream fout=new FileOutputStream("D:\\Compress\\res.txt");
DeflaterOutputStream out=new DeflaterOutputStream(fout);
int i;
while((i=fin.read())!=-1){
out.write((byte)i);
out.flush();
}
fin.close();
out.close();
}
catch(Exception e){System.out.println(e);}
System.out.println("your file compressed");
}

 
Output-

After running this program we get compressed file in same folder as below


 
res is compressed file of this pdf file if we check the size of this file it will be less then pdf actual size.


After that write code for decompress the same file as shown below,


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.InflaterInputStream;
public class Decompress {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\Compress\\res.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D:\\Compress\\D.pdf");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("your file decompressed");
}
}

Output -

And we get decompressed file in same folder as ,


Decompressed file is same as our original file.











Wednesday, 18 December 2013

String Builder

StringBuilder

StringBuilder object same as string objects, we use string builder instead of string for better performance.

StringBuilderConstructors are,

StringBuilder()
Creates an empty string builder with a capacity of 16 (16 empty elements).

StringBuilder(CharSequence cs)
Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.

StringBuilder(int initCapacity)
Creates an empty string builder with the specified initial capacity.

StringBuilder(String s)
Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.

StringBuilder Methods are,

StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)

StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)

StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)ringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)

StringBuilder reverse()

String toString()

Example a program that would be more efficient if a StringBuilder were used instead of a String-

Program for reverse string using string-


public class StringReverse {
  public static void main(String[] args) {
        String myString = "I Like Java Programming";
        int len = myString.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
       
        // put original string in an
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] =
                myString.charAt(i);
        }
       
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
       
        String reverseMyString =
            new String(charArray);
        System.out.println(reverseMyString);
    }  
}


Program for reverse string using StringBuilder reverse method-



public class StringBuilder {
   public static void main(String[] args) {
        String myString = "I Like Java Programming";
        
        StringBuilder sb = new StringBuilder(myString);
       
        sb.reverse();  // reverse it
       
        System.out.println(sb);
    }

// Constructor
    private StringBuilder(String myString) {
        throw new UnsupportedOperationException("Your method not working");
    }

    // Method
    private void reverse() {
        throw new UnsupportedOperationException("Your method not working");
       
    }
}



And Output will be same in both cases-  


Saturday, 14 December 2013

Chat Server

Chat server application in core java-


Very simple chat server application for client and server communication. Open Netbeans IDE and start develop your application. First go to file and select new project.



Select Java and list shown in another box and select Java Application
  

Create project as MyClient    
   

Click Finish.
Project structure is created as shown below,


Open MyClient.java 


Write code for client as shown below,

import java.io.*;
import java.net.*;
public class MyClient
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient()
{
   try{
s=new Socket("localhost",10);
System.out.println(s);
        din=new DataInputStream(s.getInputStream());
        dout=new DataOutputStream(s.getOutputStream()); 
clientChat();
}
catch(Exception e)
{
   System.out.println(e);
}
     }
public void clientChat()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                     String s1;
do
{
   s1=br.readLine();
                         dout.writeUTF(s1);
                         dout.flush();
                          System.out.println("server Message:"+din.readUTF());
  }
while(!s1.equals("stop"));
  }
public static void main(String ar[])
{
                          new MyClient();
}
}


After that debug your code and run it.


In run window shown your system socket ( IP Address of your machine)


After that follow same steps for creating server application


Write code for server as shown blow,

import java.io.*;
import java.net.*;
public class MyServer
{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;

public  MyServer()
{
 try{ 
System.out.println("Server Started");
ss= new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("client connected");
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{System.out.println(e);
}}
public static void main (String s[])
{ new MyServer();}
public void ServerChat() throws IOException
{
String str;
do
{
str=dis.readUTF();
System.out.println("client message "+str);
dos.writeUTF("hello dear \n"+str);
dos.flush();
}
while(!str.equals("stop"));
}}






And run server application the output window show message server started


Client is already running so in few seconds server output window will display client connected 


Go to your client run output window and write message here as, shown below and then press enter

Open server output window here client message will be display as,


In client output window message will be print which is server response 


This server handle only one client. So this is single client server, singe thread server.
If you want to run multiple client use multithread. All servers are multithreaded.











Wednesday, 4 December 2013

Android Installation

What is Android?
Android is a Linux-based operating system for mobile devices such as Smartphone and tablet computers.

Android SDK installation steps-

Operating Systems
  • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
  • Mac OS X 10.5.8 or later (x86 only)
  • Linux
Hardware requirements

The Android SDK requires disk storage for all of the components that you choose to install. 
 
Component type                                Approximate size                                 Comments
SDK Tools                                               50 MB                                           Required
Android platform (each)                           150 MB                               At least one platform is required
SDK Add-on (each)                                100 MB                                           Optional
USB Driver for Windows                         10 MB                              Optional For Windows only
Samples (per platform)                             10M                                                Optional
Offline documentation                               250 MB                                          Optional

Development Environments

Eclipse IDE
Eclipse 3.4 (Ganymede) or 3.5 (Galileo)
Download eclipse from-
Other development environments 
 
JDK 5 or JDK 6 (JRE alone is not sufficient)
Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows
Not compatible with Gnu Compiler for Java (gcj)

Download jdk 5,6 or 7 from-

Download Android SDK from-
Copy your downloaded package in your drive as,



Set environment for Jdk and androd-sdk-tools








Installing the ADT plug-in
 
1. Start Eclipse, then select Help > Install New Software.


2. In the Available Software dialog, click Add....  


3. In the Add Site dialog that appears, enter a name for the remote site (for example, "Android Plugin") in the "Name" field.
In the "Location" field, enter this URL:
If any trouble acquiring in plugin, try "http" in the URL, instead of "https"
Click OK.

4. Back in the Available Software view, you should now see "Developer Tools" added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. Click Next.
5. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. Click Next to read and accept the license agreement and install any dependencies, then click Finish.
6. Restart Eclipse.
4. Configuring the ADT Plugin

After downloaded ADT the next step is to modify ADT preferences in Eclipse to point to the Android SDK directory-
 
1. Select Window > Preferences... to open the Preferences panel 
2. Select Android from the left panel.  
3. For the SDK Location in the main panel, click Browse... and locate downloaded SDK directory.
4. Click Apply, then OK. 
Adding Android platform 
The last step is to use AVD manager to install various components into development environment.
5. Launching from Eclipse/ADT

If you are developing in Eclipse and have already installed the ADT Plugin, follow these steps to access the
Android SDK and AVD Manager tool.

1. Open Eclipse
2. Select Window > Android SDK and AVD Manager.


3. Select Available Packages in the left panel. This will reveal all of the components that are currently available for download from the SDK repository.



4. Select the component(s) you'd like to install and click Install Selected.
5. Verify and accept the components you want and click Install Accepted. The components will now be installed into your existing Android SDK directories. New platforms are automatically saved into the <sdk>/platforms/ directory of your SDK; new add-ons are saved in the <sdk>/add-ons/ directory; samples are saved in the <sdk>/samples/android-<level>/; and new documentation is saved in the existing <sdk>/docs/ directory (old docs are replaced). 


 










Now your Android development environment is ready to use.