String Tokenizer in Java II

Refer the first post on String Tokenizer here.

Lets play with a little complicated string in this post! This will just demonstrate how you can use Tokenizer in more often encountered string parsing situations.

Lets run....



package org.chandan.string.tokenizer;

import java.util.StringTokenizer;

public class StringTokenizerSample {

/*
* Notice that, first we need to tokenize with respect to ';' as
* delimiter.
* Then on generated tokens, we have to again tokenize
* with '=' as delimiter.
*/
private static final String SAMPLE_STRING_1=
    "name=myName;address=myAddress;phone=myPhone";

private static final String DELIM_EQUAL="=";

private static final String DELIM_SEMICOLON=";";
 
public static void main(String args[])
{
       System.out.println("PROCESSING STRING =     ["+SAMPLE_STRING_1+"]");
       System.out.println("----------------------------------------");
       processString(SAMPLE_STRING_1,DELIM_SEMICOLON,DELIM_EQUAL);
    System.out.println("");
    System.out.println("*********************************************");
}

private static void processString(String sample,String     delimiter1
,String delimiter2)
{
/*
* First tokenize whole string with respect to first delimeter.
* Then iterate over generated tokens to perform further tokenization.
*/
    StringTokenizer stringTokenizer=new    StringTokenizer(sample,delimiter1);
    System.out.println("TOTAL NO OF MAIN TOKENS FOUND: "
   +stringTokenizer.countTokens());
    int tokenCount=1;
   while(stringTokenizer.hasMoreElements())
   {
     String mainToken=stringTokenizer.nextElement().toString();
     System.out.println("");
     System.out.println("MAIN TOKEN["+tokenCount++ +"] -> "
+mainToken);
     System.out.println(".................................");
    StringTokenizer stringTokenizer2=new StringTokenizer(
mainToken,delimiter2);
    System.out.println("");
    System.out.println("TOTAL NO OF SUB TOKENS FOUND: "
    +stringTokenizer2.countTokens());
    int subTokenCount=1;
    while (stringTokenizer2.hasMoreElements())
    {
        System.out.println("SUB TOKEN["+subTokenCount++ +"] -> "
        +stringTokenizer2.nextElement());
     }//END OF INNER WHILE LOOP
   }//END OF OUTER WHILE LOOP
  }//END OF METHOD
}



OUTPUT:

PROCESSING STRING = [name=myName;address=myAddress;phone=myPhone]
----------------------------------------
TOTAL NO OF MAIN TOKENS FOUND: 3

MAIN TOKEN[1] -> name=myName
.................................

TOTAL NO OF SUB TOKENS FOUND: 2
SUB TOKEN[1] -> name
SUB TOKEN[2] -> myName

MAIN TOKEN[2] -> address=myAddress
.................................

TOTAL NO OF SUB TOKENS FOUND: 2
SUB TOKEN[1] -> address
SUB TOKEN[2] -> myAddress

MAIN TOKEN[3] -> phone=myPhone
.................................

TOTAL NO OF SUB TOKENS FOUND: 2
SUB TOKEN[1] -> phone
SUB TOKEN[2] -> myPhone

*********************************************

If you are looking for some tutorials on parsing an xml document, then check HERE.


Happy coding :)



.

String Tokenizer in Java I

You may come across a situation where in small string has to be parsed with respect to some delimiters instead of entire file.

Wait.. Don't just jump to code by looking character by character...that's tedious to do..isn't it?

Be smart enough to use well defined and built in classes & methods which serve your purpose :-)

I am telling about "java.util.StringTokenizer" class! Lets understand its capacity with a small example...


package org.chandan.string.tokenizer;

import java.util.StringTokenizer;

public class StringTokenizerSample {

   //Your String to be tokenized.
   private static final String SAMPLE_STRING_1=
   "a1,A2,a3,A4,a5";

   //delimiter used to tokenize.
   private static final String DELIM_COMMA=",";

   public static void main(String args[])
   {
     System.out.println("PROCESSING STRING = ["+SAMPLE_STRING_1+"]");
      System.out.println("----------------------------------------");

     processString(SAMPLE_STRING_1,DELIM_COMMA);

     System.out.println("");
     System.out.println("*********************************************");
  }

  private static void processString(String sample,String delimiters)
  {
      StringTokenizer stringTokenizer=new StringTokenizer(sample,delimiters);
      System.out.println("TOTAL NO OF TOKENS FOUND: "
      +stringTokenizer.countTokens());
      int tokenCount=1;

     while(stringTokenizer.hasMoreElements())
    {
       System.out.println("TOKEN["+tokenCount+"] = "
       +stringTokenizer.nextElement());
    }
  }

}


OUTPUT:

PROCESSING STRING = [a1,A2,a3,A4,a5]
----------------------------------------
TOTAL NO OF TOKENS FOUND: 5
TOKEN[1] = a1
TOKEN[2] = A2
TOKEN[3] = a3
TOKEN[4] = A4
TOKEN[5] = a5

*********************************************


If you are looking for some tutorials on parsing an xml document, then check HERE.

Still hungry...? Check next post on Tokenizer here

Got doubts ? Post as comments....Lets find solution together!
Happy coding :)


.

Unzipping the zipped file stored in server into your Android application


Explaining along with the code snippet would be better+smarter+shortcut,  and 'm practising the same below ;-)

package org.sample.example.download;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.content.Context;
import android.util.Log;

public class UnzipManager {

       private static String BASE_FOLDER;

       public static Context localContext;
       /*
       *You can use this flag to check whether Unzipping
       *thread is still running..
       */
       public static boolean isDownloadInProgress;
       /*
        * After unzipping using this flag ,you can check
        * whether any low memory exceptions
        * Occurred or not..and alert user accordingly..
        */
       public static boolean isLowOnMemory;
 
     public static void startUnzipping()
      {
             /*
             * MAKE SURE THAT localContext VARIABLE HAS BEEN
             * INITIALIZED BEFORE INVOKING THIS METHOD.
             *
             * ALSO MAKE SURE YOU HAVE SET "INTERNET" AND
             * "NETWORK ACCESS STATE" PERMISSIONS IN
             * APPLICATION'S MANIFEST FILE.
             *
             */
             Log.d("DEBUG","In startUnzipping()");
             UnzipManager.BASE_FOLDER=UnzipManager.localContext.getFilesDir().getPath();
            /*
            *
            */
            Log.d("DEBUG","BASE_FOLDER:"+UnzipManager.BASE_FOLDER);
           UnzipManager.isLowOnMemory=false;
           //Start unzipping in a thread..which is safer
           //way to do high cost processes..
           new UnzipThread().start();
    }

    private static class UnzipThread extends Thread{
             @Override
           public void run()
          {
                     UnzipManager.isDownloadInProgress=true;
                     Log.d("DEBUG","Unzipping----------------------------");
                 URLConnection urlConnection ;
                 try
                {
                      /************************************************
                      *
                      * IF you are unzipping a zipped file save under
                      * some URL in remote server
                      * **********************************************/
                     URL finalUrl =new URL("http://www.temp.org/folder1/file_name.zip"
                           /* Url string where the zipped file is stored...*/);
                     urlConnection = finalUrl.openConnection();

                    //Get the size of the ( zipped file's) inputstream from server..
                         int contentLength=urlConnection.getContentLength();
                         Log.d("DEBUG", "urlConnection.getContentLength():"+contentLength);
                    /*****************************************************
                     *
                     * YOU CAN GET INPUT STREAM OF A ZIPPED FILE FROM
                     * ASSETS FOLDER AS WELL..,IN THAT CASE JUST PASS THAT
                     * INPUTSTEAM OVER HERE...MAKE SURE YOU
                     * HAVE SET STREAM CONTENT LENGTH OF THE SAME..
                     *
                     ******************************************************/
                     ZipInputStream zipInputStream = new                  ZipInputStream(urlConnection.getInputStream());
                     /*
                      * Iterate over all the files and folders
                      */
                     for (ZipEntry zipEntry = zipInputStream.getNextEntry();
                           zipEntry != null; zipEntry = zipInputStream.getNextEntry())
                          {
                              Log.d("DEBUG","Extracting: " + zipEntry.getName() + "...");

                             /*
                              * Extracted file will be saved with same
                              * file name that in zipped folder.
                              */
                                String innerFileName = BASE_FOLDER + File.separator + zipEntry.getName();
                                File innerFile = new File(innerFileName);
                                 /*
                                  * Checking for pre-existence of the file and
                                  * taking necessary actions
                                  */
                                if (innerFile.exists())
                                {
                                       Log.d("DEBUG","The Entry already exits!, so deleting..");
                                       innerFile.delete();
                                 }

                                /*
                                 * Checking for extracted entry for folder
                                 * type..and taking necessary actions
                                 */
                                if (zipEntry.isDirectory())
                                {
                                     Log.d("DEBUG","The Entry is a directory..");
                                     innerFile.mkdirs();
                                }
                                else
                               {
                                  Log.d("DEBUG","The Entry is a file..");
                                  FileOutputStream outputStream = new FileOutputStream(innerFileName);
                                  final int BUFFER_SIZE = 2048;

                                /*
                                * Get the buffered output stream..
                               
                                */
                                 BufferedOutputStream bufferedOutputStream =
                                  new BufferedOutputStream(outputStream,BUFFER_SIZE);
                                         /*
                                         * Write into the file's buffered output stream ,..
                                         */
                                        int count = 0;
                                        byte[] buffer = new byte[BUFFER_SIZE];
                                        while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1)
                                        {
                                               bufferedOutputStream.write(buffer, 0, count);
                                        }
                                         /***********************************************
                                         * IF YOU WANT TO TRACK NO OF FILES DOWNLOADED,
                                         * HAVE A STATIC COUNTER VARIABLE, INITIALIZE IT
                                         * IN startUnzipping() before calling startUnZipping(),
                                         * AND INCREMENT THE COUNTER VARIABLE
                                         * OVER HERE..LATER YOU CAN USE VALUE OF
                                         * COUNTER VARIABLE TO CROSS VERIFY WHETHER ALL
                                         * ZIPPED FILES PROPERLY UNZIPPED AND SAVED OR NOT.
                                         *
                                        * ************************************************
                                        */
                                        /*
                                         * Handle closing of output streams..
                                         */
                                         bufferedOutputStream.flush();
                                         bufferedOutputStream.close();
                                  }
                                 /*
                                  * Finish the current zipEntry
                                  */
                                 zipInputStream.closeEntry();
                          }
                          /*
                          * Handle closing of input stream...
                          */
                           zipInputStream.close();
                           Log.d("DEBUG","--------------------------------");
                           Log.d("DEBUG","Unzipping completed..");
                     }
                     catch (IOException e)
                    {
                             Log.d("DEBUG","Exception occured: " + e.getMessage());
                            if(e.getMessage().equalsIgnoreCase("No space left on device"))
                                  {
                                         UnzipManager.isLowOnMemory=true;
                           }
                           e.printStackTrace();
                   }
                   UnzipManager.isDownloadInProgress=false;
            }
       };
}


I have studied unzipping a file from here.

Happy coding guys :)

.