Reading Excel Sheet Documents in Java


For some reason i found Apache POI difficult to use for reading excel sheet, in terms of naming conventions and the code so i was searching for another Library for reading Excel Sheet in Java and i stopped at JXL.
Java Excel API namely JXL is an Java based API that allows us to read/write/edit the Excel Sheet. The main think i liked about it was its simplicity over Apache POI Package. This article will show you how we can read Excel Sheet using JXL.

Now here i am going to read an excel sheet having content:

EmpId Name Designation

1

ABC

Software Engineer

2

DFG

Sr Software Engineer

3

LOI

Team Leader

4 LKJ Project Manager
5 QWE Software Architech

I have uploaded the same excel sheet on the server you can download it from here: Download Excel Sheet

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.DateCell;
public class ReadXLSheet {
    public void init(String filePath) {
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(new File(filePath));
            contentReading(fs);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //Returns the Headings used inside the excel sheet
    public void getHeadingFromXlsFile(Sheet sheet) {
        int columnCount = sheet.getColumns();
        for (int i = 0; i < columnCount; i++) {
            System.out.println(sheet.getCell(i, 0).getContents());
        }
    }
    public void contentReading(InputStream fileInputStream) {
        WorkbookSettings ws = null;
        Workbook workbook = null;
        Sheet s = null;
        Cell rowData[] = null;
        int rowCount = ‘0’;
        int columnCount = ‘0’;
        DateCell dc = null;
        int totalSheet = 0;
        try {
            ws = new WorkbookSettings();
            ws.setLocale(new Locale("en", "EN"));
            workbook = Workbook.getWorkbook(fileInputStream, ws);
            totalSheet = workbook.getNumberOfSheets();
            if(totalSheet > 0) {
                System.out.println("Total Sheet Found:" + totalSheet);
                for(int j=0;j<totalsheet ;j++) {
                    System.out.println("Sheet Name:" + workbook.getSheet(j).getName());
                }
            }
            //Getting Default Sheet i.e. 0
            s = workbook.getSheet(0);
            //Reading Individual Cell
            getHeadingFromXlsFile(s);
            //Total Total No Of Rows in Sheet, will return you no of rows that are occupied with some data
            System.out.println("Total Rows inside Sheet:" + s.getRows());
            rowCount = s.getRows();
            //Total Total No Of Columns in Sheet
            System.out.println("Total Column inside Sheet:" + s.getColumns());
            columnCount = s.getColumns();
            //Reading Individual Row Content
            for (int i = 0; i < rowCount; i++) {
                //Get Individual Row
                rowData = s.getRow(i);
                if (rowData[0].getContents().length() != 0) { // the first date column must not null
                    for (int j = 0; j < columnCount; j++) {
                        switch (j) {
                        case 0:
                            System.out.println("Employee Id:" + rowData[j].getContents());
                        case 1:
                            System.out.println("Employee Name:" + rowData[j].getContents());
                        case 2:
                            System.out.println("Employee Designation:" + rowData[j].getContents());
                        default:
                            break;
                        }
                    }
                }
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }
        public static void main(String[] args) {
        try {
            ReadXLSheet xlReader = new ReadXLSheet();
            xlReader.init("/home/hitesh/Desktop/test.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

Total Sheet Found:3
----------------------------------------------
Sheet Name:Sheet1
Sheet Name:Sheet2
Sheet Name:Sheet3
----------------------------------------------
Column Heading:EmpId
Column Heading:Name
Column Heading:Designation
----------------------------------------------
Total Rows inside Sheet:6
----------------------------------------------
Total Column inside Sheet:3
----------------------------------------------
Employee Id:EmpId
Employee Name:Name
Employee Designation:Designation
----------------------------------------------
Employee Id:1
Employee Name:ABC
Employee Designation:Software Engineer
----------------------------------------------
Employee Id:2
Employee Name:DFG
Employee Designation:Sr Software Engineer
----------------------------------------------
Employee Id:3
Employee Name:LOI
Employee Designation:Team Leader
----------------------------------------------
Employee Id:4
Employee Name:LKJ
Employee Designation:Project Manager
----------------------------------------------
Employee Id:5
Employee Name:QWE
Employee Designation:Software Architect

 

With respect to the following code written i am able to perform the following operation:

  • Calculate total no of Sheets inside the Excel Sheet
  • List all the Sheet Name used inside Excel Sheet
  • Read Individual Cell for specifying the cell position – in code have read the column heading i.e. 1st row
  • Read Total Modified Rows in the Excel Sheet
  • Read Total Modified Columns in the Excel Sheet
  • Read Individual Row Content

 

Source : Techie Zone Blog

Advertisements

Face detection for Camera


Long long time ago(2010-05-19), I have a post "Android FaceDetector" about how to use android.media.FaceDetector to identify faces in a Bitmap.
Start from Android 4, API Level 14, the android.hardware.Camera class provide the feature of Face Detection. You can build apps to detect face on camera at live.

image

The method startFaceDetection() starts the face detection. This should be called after preview is started. The camera will notify Camera.FaceDetectionListener of the detected faces in the preview frame. The detected faces may be the same as the previous ones. Applications should call stopFaceDetection() to stop the face detection. This method is supported if getMaxNumDetectedFaces() returns a number larger than 0. If the face detection has started, apps should not call this again.
When the face detection is running, setWhiteBalance(String), setFocusAreas(List), and setMeteringAreas(List) have no effect. The camera uses the detected faces to do auto-white balance, auto exposure, and autofocus.


If the apps call autoFocus(AutoFocusCallback), the camera will stop sending face callbacks. The last face callback indicates the areas used to do autofocus. After focus completes, face detection will resume sending face callbacks. If the apps call cancelAutoFocus(), the face callbacks will also resume.
After calling takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback) or stopPreview(), and then resuming preview with startPreview(), the apps should call this method again to resume face detection.

It’s modify from the exercise "Start Camera auto-focusing, autoFocus()" to add function of face detection.
Modify main.xml to add a SurfaceView for camera preview, and a TextView to display the number of face detected.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />
   <TextView
       android:id="@+id/prompt"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"/>
   <SurfaceView
       android:id="@+id/camerapreview"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" />

</LinearLayout>

 

Create /res/layout/control.xml, it’s a view overlap with the preview SurfaceView, to provide a button to take picture.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom"
>
<Button
android:id="@+id/takepicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" * Take Picture "
android:layout_gravity="right"
android:layout_margin="10px"
/>
</LinearLayout>

 

Main code, call camera.startFaceDetection() after camera.startPreview(), and call camera.stopFaceDetection() before camera.stopPreview(), also define our FaceDetectionListener to display the result of number of face detected.

package com.exercise.AndroidCamera;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AndroidCamera extends Activity implements SurfaceHolder.Callback{

Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;

Button buttonTakePicture;
TextView prompt;

final int RESULT_SAVEIMAGE = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);

buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});

LinearLayout layoutBackground = (LinearLayout)findViewById(R.id.background);
layoutBackground.setOnClickListener(new LinearLayout.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback);
}});

prompt = (TextView)findViewById(R.id.prompt);
}

FaceDetectionListener faceDetectionListener
= new FaceDetectionListener(){

@Override
public void onFaceDetection(Face[] faces, Camera camera) {

if (faces.length == 0){
prompt.setText(" No Face Detected! ");
}else{
prompt.setText(String.valueOf(faces.length) + " Face Detected :) ");
}


}};

AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){

@Override
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(true);
}};

ShutterCallback myShutterCallback = new ShutterCallback(){

@Override
public void onShutter() {
// TODO Auto-generated method stub

}};

PictureCallback myPictureCallback_RAW = new PictureCallback(){

@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub

}};

PictureCallback myPictureCallback_JPG = new PictureCallback(){

@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */

Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();

prompt.setText("Image saved: " + uriTarget.toString());

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


camera.startPreview();
camera.startFaceDetection();
}};

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopFaceDetection();
camera.stopPreview();
previewing = false;
}

if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();

prompt.setText(String.valueOf(
"Max Face: " + camera.getParameters().getMaxNumDetectedFaces()));
camera.startFaceDetection();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setFaceDetectionListener(faceDetectionListener);
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopFaceDetection();
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

 

Modify AndroidManifest.xml, to add permission of "android.permission.CAMERA", and set android:minSdkVersion="14".

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidCamera"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.CAMERA"/>

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidCamera"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

 

Download Source : Here

SOURCE : Android-er

Native Method example using JNI


Trivial JNI example

  1. Declare your native methods in an otherwise normal Java class.
    public class nativetest
    {
    	public native String sayHello(String s);
    	public static void main(String[] argv)
    	{
    		String retval = null;
    		nativetest nt = new nativetest();
    		retval = nt.sayHello("Beavis");
    		System.out.println("Invocation returned " + retval);
    	}
    }
    
  2. javac nativetest.java
    Standard Java compile
  3. javah -jni nativetest
    Generates .h files. Here is the code.
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include 
    /* Header for class nativetest */
    
    #ifndef _Included_nativetest
    #define _Included_nativetest
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     nativetest
     * Method:    sayHello
     * Signature: (Ljava/lang/String;)Ljava/lang/String;
     */
    JNIEXPORT jstring JNICALL Java_nativetest_sayHello
      (JNIEnv *, jobject, jstring);
    
    #ifdef __cplusplus
    }
    #endif
    #endif
    
  4. Write your native code, using the .h file generated above Copy the function prototype from the .h file and paste it in.
    #include "nativetest.h"	/*double quotes tells it to search current directory*/
    
    JNIEXPORT jstring JNICALL Java_nativetest_sayHello
      (JNIEnv *env, jobject thisobject, jstring js)
    
    {
    	return js;
    }
    
  5. Compile
    cl -c /Ic:\jdk1.1.6\include /Ic:\jdk1.1.6\include\win32 nativetest.c 
    link /libpath=c:\jdk1.1.6\lib nativetest.obj /dll
    

    The above uses Microsoft Visual C++ command-line tools.

  6. Modify your Java class to load the library.
    public class nativetest
    {
    	static {
    		System.loadLibrary("nativetest");
    	}
    	public native String sayHello(String s);
    	public static void main(String[] argv)
    	{
    		String retval = null;
    		nativetest nt = new nativetest();
    		retval = nt.sayHello("Beavis");
    		System.out.println("Invocation returned " + retval);
    	}
    }
    
  7. run the example
    C:\jni\hello>java nativetest
    Invocation returned Beavis
    

Source : http://patriot.net/~tvalesky/jninative.html

Checking for WiFi Access (Kiểm tra sự tồn tại của Wifi)


Returns true if any WiFi access point is available in the vicinity of the device, else False

(Trả về true nếu có điểm truy cập Wifi ngược lại trả về false)

public boolean IsNetworkAvailable(Context context){
                   ConnectivityManager connectivity = (ConnectivityManager)
                                   context.getSystemService(Context.CONNECTIVITY_SERVICE);
                   if (connectivity == null) {
                  Toast.makeText(context, “None Available”, Toast.LENGTH_SHORT).show();
                   } else {
                      NetworkInfo[] info = connectivity.getAllNetworkInfo();
                      for(NetworkInfo inf : info){
                          if(inf.getTypeName().contains(“WIFI”))
                                  if(inf.isConnected())
                                          return true;
                      }
                   }
                   return false;
        }

How to Make an Activity Fullscreen (Làm thế nào để 1 Activity Full màn hình)


This code makes the current Activity Full-Screen. No Status-Bar or anything except the Activity-Window!

(Đây là đoạn code giúp Activity hiện tại Toàn màn hình. Không có status bar và tiêu đề..)

public class FullScreen extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);
    }
}

ServicesDemo – Using Android Services


To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).
Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service.
context.startService() | ->onCreate() – >onStartCommand() [service running]
Calling the applications stopService() method to stop the service.
context.stopService() | ->onDestroy() [service stops]
Something that we didn’t use in this example is bindService() which just calls the services onCreate() method but does not call the onStartCommand(). onBindService() is used to create persistance connection to the service.
context.onBindService() | ->onCreate() [service created]
This Services Demo is simple as it plays a audio file and by listening to click events of the buttons invokes the MyService service.

 

ServicesDemo.java

package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
  private static final String TAG = “ServicesDemo”;
  Button buttonStart, buttonStop;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, “onClick: starting srvice”);
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, “onClick: stopping srvice”);
      stopService(new Intent(this, MyService.class));
      break;
    }
  }
}

To understand the audiomedia player, please review the AudioDemo posted in this form. The custom MyService extends Service class and necessary to override various methods of its lifecycle ie onCreate(), onStartCommand(), or onDestroy()
MyService.java

package com.example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = “MyService”;
    MediaPlayer player;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, “My Service Created”, Toast.LENGTH_LONG).show();
        Log.d(TAG, “onCreate”);
        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false); // Set looping
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, “My Service Stopped”, Toast.LENGTH_LONG).show();
        Log.d(TAG, “onDestroy”);
        player.stop();
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, “My Service Started”, Toast.LENGTH_LONG).show();
        Log.d(TAG, “onStart”);
        player.start();
    }
}

Necessary to let the AndroidManifest file know about your service <service android:enabled="true" android:name=".MyService" />
AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
  package=”com.example” android:versionCode=”1″ android:versionName=”1.0″>
  <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
    <activity android:name=”.ServicesDemo” android:label=”@string/app_name”>
      <intent-filter>
        <action android:name=”android.intent.action.MAIN” />
        <category android:name=”android.intent.category.LAUNCHER” />
      </intent-filter>
    </activity>
    <service android:enabled=”true” android:name=”.MyService” />
  </application>
  <uses-sdk android:minSdkVersion=”3″ />
</manifest>

main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:orientation=”vertical”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:gravity=”center”>
<TextView 
    android:layout_width=”fill_parent”
    android:layout_height=”wrap_content” android:text=”Services Demo” android:gravity=”center” android:textSize=”20sp” android:padding=”20dp”/>
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/buttonStart” android:text=”Start”></Button>
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Stop” android:id=”@+id/buttonStop”></Button>
</LinearLayout>

Output

image

Java’s UTF-8 and Unicode writing is broken – Use this fix


Many of you might not believe this but try creating a file in UTF-8 encoding using a java program like this one (found on the java tutorial site)

//example from Sun – Incorrect output
static void writeOutput(String str) {

try {
FileOutputStream fos = new FileOutputStream(“test.txt”);
Writer out = new OutputStreamWriter(fos, “UTF8”);
out.write(str);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

 

This will create a file alright, but that file will not be a true UTF-8 file. Infact, this is a known and documented bug in the JDK that SUN will never fix!
There are other problems with the java.io package when it comes to unicode, for example, the OutputStreamWriter will not write an ASCII stream correctly leaving a ‘?’ at the beginning of the output stream if input stream was Unicode.
After scouring the internet for information on how to get around this, I decided to write a general purpose Unicode converter that would convert FROM and TO any of the following formats:
UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE, ASCII
Usage:
byte[] outbytes = UnicodeUtils.convert(byte[] inbytes, String desiredoutputEncoding);
(The convertor will auto-sense the encoding of the input bytes)
The famous Shanghai Example:

//Example of usage:
String shanghai = “\u4E0A\u6D77”;
byte[] out = UnicodeUtil.convert(shanghai.getBytes(“UTF-16”), “UTF-8”); //Shanghai in Chinese
FileOutputStream fos = new FileOutputStream(“/tmp/out.htm);
fos.write(out);
fos.close();

 

The following is the code for UnicodeUtils.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class UnicodeUtil {

public static byte[] convert(byte[] bytes, String encout) throws Exception {
// Workaround for bug that will not be fixed by SUN
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
UnicodeInputStream uis = new UnicodeInputStream(new ByteArrayInputStream(bytes), “ASCII”);
boolean unicodeOutputReqd = (getBOM(encout) != null) ? true : false;
String enc = uis.getEncoding();
String BOM = getBOM(enc); // get the BOM of the inputstream

if (BOM == null) {
// inputstream looks like ascii…
// create a BOM based on the outputstream
BOM = getBOM(encout);
}
uis.close();

ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes, uis.getBOMOffset(), bytes.length), enc));
Writer w = new BufferedWriter(new OutputStreamWriter(out, encout));

// dont write a BOM for ascii(out) as the OutputStreamWriter
// will not process it correctly.
if (BOM != null && unicodeOutputReqd) {
w.write(BOM);
}

char[] buffer = new char[4096];
int len;
while ((len = br.read(buffer)) != -1) {
w.write(buffer, 0, len);
}

br.close(); // Close the input.
w.close(); // Flush and close output.
return out.toByteArray();
}

public static String getBOM(String enc) throws UnsupportedEncodingException {
if (“UTF-8”.equals(enc)) {
byte[] bom = new byte[3];
bom[0] = (byte) 0xEF;
bom[1] = (byte) 0xBB;
bom[2] = (byte) 0xBF;
return new String(bom, enc);
} else if (“UTF-16BE”.equals(enc)) {
byte[] bom = new byte[2];
bom[0] = (byte) 0xFE;
bom[1] = (byte) 0xFF;
return new String(bom, enc);
} else if (“UTF-16LE”.equals(enc)) {
byte[] bom = new byte[2];
bom[0] = (byte) 0xFF;
bom[1] = (byte) 0xFE;
return new String(bom, enc);
} else if (“UTF-32BE”.equals(enc)) {
byte[] bom = new byte[4];
bom[0] = (byte) 0x00;
bom[1] = (byte) 0x00;
bom[2] = (byte) 0xFE;
bom[3] = (byte) 0xFF;
return new String(bom, enc);
} else if (“UTF-32LE”.equals(enc)) {
byte[] bom = new byte[4];
bom[0] = (byte) 0x00;
bom[1] = (byte) 0x00;
bom[2] = (byte) 0xFF;
bom[3] = (byte) 0xFE;
return new String(bom, enc);
} else {
return null;
}

}

public static class UnicodeInputStream extends InputStream {
private PushbackInputStream internalIn;

private boolean isInited = false;

private int BOMOffset = -1;

private String defaultEnc;

private String encoding;

public static final int BOM_SIZE = 4;

public UnicodeInputStream(InputStream in, String defaultEnc) {
internalIn = new PushbackInputStream(in, BOM_SIZE);
this.defaultEnc = defaultEnc;
}

public String getDefaultEncoding() {
return defaultEnc;
}

public String getEncoding() {
if (!isInited) {
try {
init();
} catch (IOException ex) {
IllegalStateException ise = new IllegalStateException(“Init method failed.”);
ise.initCause(ise);
throw ise;
}
}
return encoding;
}

/**
* Read-ahead four bytes and check for BOM marks. Extra bytes are unread
* back to the stream, only BOM bytes are skipped.
*/
protected void init() throws IOException {
if (isInited)
return;

byte bom[] = new byte[BOM_SIZE];
int n, unread;
n = internalIn.read(bom, 0, bom.length);

if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
encoding = “UTF-32BE”;
unread = n – 4;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
encoding = “UTF-32LE”;
unread = n – 4;
} else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
encoding = “UTF-8”;
unread = n – 3;
} else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
encoding = “UTF-16BE”;
unread = n – 2;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
encoding = “UTF-16LE”;
unread = n – 2;
} else {
// Unicode BOM mark not found, unread all bytes
encoding = defaultEnc;
unread = n;
}
BOMOffset = BOM_SIZE – unread;
if (unread > 0)
internalIn.unread(bom, (n – unread), unread);

isInited = true;
}

public void close() throws IOException {
// init();
isInited = true;
internalIn.close();
}

public int read() throws IOException {
// init();
isInited = true;
return internalIn.read();
}

public int getBOMOffset() {
return BOMOffset;
}
}

}

 

Source : http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html