Read and Write Files -

Hey folks! I'm back with another simple how-to-do tip. This time I'm going to talk about very common library in Java SE. That is package. When you coding your Java application, there are some situation you might need to read or write a file from/into the local disk. Believe me or not, everytime I need it, I always ended up with googling it :D So I thought it will be really useful if I can do a simple example and publish it in the blog.

Okay, what I'm going to do today is write an app to read text files from the local disk and write it back to the disk with modified changes. Destination file may be the same source file or a new text file. Lets get our hands dirty.

File reading

File writing
File filter
This will filter the text files(.txt) from your local disk and ignore other file types.
Final app

Note: I have removed all the exception handling codes for more clarity. So make sure you handle I/O exceptions appropriately. I haven't talked much about GUI codes here as well and I assume that you already familiar with Java Swing stuff. You can get the full source code from my git repo.

Git url:

That's it folks! Don't forget to give me your feedback and please let me know if there are any mistakes. See you soon. Byee!

JPA persist() Vs merge()

Last week I was working in our project at office and I came across this confusion between these two buddies. Even I have been working with hibernate, I found that its bit difficult to think about this in hibernate aspect. Because JPA has its own set of methods to save objects which are not same as in hibernate. Lets find out how these methods works using an simpleexample. 

Create a new student object
Get an entity manager instance from the persistence.xml file
Save a student object using persist()
name -> "Saman"
age -> 24

When we call persist on that new student instance, It will do following things.
1. Object added to persistence context as new entity(Make an instance managed)
2. New entity inserted into database at flush/commit

Save a student object using merge()
name -> "Saman"
age -> 12

When we call persist on that new student instance, It will do following things.
1. State copied to new entity.
2. New entity added to persistence context
3. New entity inserted into database at flush/commit
4. New entity returned

So if we want to update new entity using merge(), we can do something like this.
name -> "Saman"
age -> 24

Git url for demo project:

Following links helped me to understand this difference and all the credits should go to its authors.

 Hope this helps you. See you next time. Bye! :D

JTable and bean binding

Hello everyone! After a long pause, here I am again :) Thought to power the blog again with the experience which I have gained past couple of years and hope to keep this as a future reference to me as well to remember what I have learned/gained during my work/study.

Okay! Let me begin the post. I have come across this scenario while I was working on a Java Swing application project at my office.

The problem: How to populate JTable with list of objects.

Typical and painful solution: Loop through the list and populate data column by column.
But it's a real pain when it comes to retrieve data as objects again from the table. We have to extract each property from each column in the table and create a new object with that data.

An easy and less complex/code solution: Bind beans to the table as rows.
If we can bind objects as it is to the table then its really easy to retrieve them as well. No need to iterate through columns anymore. I found this solution from this blog and total credit goes to the author.

This is how it works. There are two ways to bind beans to JTable.
  • Bean Table Model
  • Row Table Model
I have included both ways in the sample project please find the url for git repo at the end of this post. But here I only explain first method. Its really easy to understand second method once you learn the first. In the sample project, its just a matter of changing table model implementation in the source file to switch between those two methods.I have included all the source files in one package.

Following steps explain how to do it.

Step 1: Create a bean class
Step 2: Create the bean table model
Step 3: Bind the table model with JTable
Step 4: Retrieve data from the table
Screenshot of the demo application:
Yep. That's all. Its simple as that. Okay, time to go to bed :) I'll see you in another post. Triple gem bless you!

Git repository URL: JTableBeanDemo

P.S: You can also get the original source files from the blog link i have mentioned in the post.

How to build a Java Swing You Tube Player

Few days ago, I wanted to write a simple you tube player in java. I searched the internet and ultimately found few relevant articles. not much :(
but this article motivate me to find out more details about creating the player.
finally i found out a way!

First of all I have to tell you that these all codes are belongs to Sun Micro systems and for more details click this link

These codes can be downloaded from the above site and read all the page content and then you can understand how it goes.

What is JDIC ?

The JDesktop Integration Components (JDIC) project aims to make Java™ technology-based applications ("Java applications") first-class citizens of current desktop platforms without sacrificing platform independence. Its mission is to enable seamless desktop/Java integration.

JDIC provides Java applications with access to functionalities and facilities provided by the native desktop. It consists of a collection of Java packages and tools. JDIC supports a variety of features such as embedding the native browser,
launching the desktop applications, creating tray icons on the desktop, registering file type associations, creating JNLP installer packages, etc.

JDICplus project

Currently the JDICplus is a Java Win32-extension development kit, enabling developers to use extended Microsoft Windows API functionality. Mainly the project implements the semi-lightweight wrapper component around Microsoft Internet Explorer (IE).

Demo Application(A You Tube player and many more features)


Instructions to execute and build:

1.) Go to this link

2.) Download both zip files which contain binary execution

files and source files and extract into your hard drive.

3.) To run demos, just double click .jar files in the binary

zip file

4.) To build samples, I used Netbenas IDE and it'll build
without any single error :)

For an example, Go to folder called 'demo' in the source zip file. It contains source files for several samples that you have executed in the 3rd step.
In here i explain how to build 'FlashPlayer' sample

- Open a new project in the Netbeans
- Add a new Java class same as to the java file name in that sample foldercalled 'FlashPlayer'
- Then copy all the source code in that java file into the newly created class body.(do not modify the package declaration)
- Next, go to folder that you have extracted from binary demo zip file. In that folder, go to another folder called 'Lib'
- In the outside of the folder you can see it contain 3 .jar files. Add those jar files into the library of the netbeans project.(I assume that you know how to add libraries to a netbenas project)
- Congratulations ! You have successfully configure all the settings.
- Now, run the project. It appears nice, cute java swing frame with 3 buttons. Click 'Sample Movie (FLV)' button to play a vedio from the You Tube. Check out the oher 2 buttons also.

If you want to play a different video from the you tube, just go to the source and change the video id in relevant places (with in the html syntax)

Enjoy !!! I'll see you later
Have a nice weekend

Sun blueprint : How to run petstore app

hi everyone,

ohh....finally it's worked for me.
I just downloaded javaee sdk with blueprints(~100mb) setup from sun website.
here is the link -
Then follow the instruction they given with blueprint's about page.
I didnt change anything in file. because default settings worked for me.
What i did was
1) Add /lib/ant/bin directory to your PATH environment variable
2) adde JAVA_HOME system variable and set it to "C:\Program Files\Java\jdk1.6.0_03".(dont put quotes)

Then open the cmd

3) Change to the blueprints/petstore/directory
4) Enter the command:
ant setup
ant run
This will build the application, deploy it on the application server, and then launch the project's URL in your default browser (for example http://localhost:8080/petstore).

That really worked for me and finall my browser automatically opend and dispaly index page of the petstore app !!!


Java mobile application

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Jargoneer extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Command mExitCommand, mFindCommand, mCancelCommand;
private TextBox mSubmitBox;
private Form mProgressForm;
private StringItem mProgressString;
public Jargoneer() {
mExitCommand = new Command("Exit", Command.EXIT, 0);
mFindCommand = new Command("Find", Command.SCREEN, 0);
mCancelCommand = new Command("Cancel", Command.CANCEL, 0);
mSubmitBox = new TextBox("Jargoneer", "", 32, 0);
mProgressForm = new Form("Lookup progress");
mProgressString = new StringItem(null, null);
public void startApp() {
mDisplay = Display.getDisplay(this);
try {
String baseURL = "";
String url = baseURL + word;
hc = (HttpConnection);
hc.setRequestProperty("Connection", "close");
in = hc.openInputStream();
int contentLength = (int)hc.getLength();
if (contentLength == -1) contentLength = 255;
byte[] raw = new byte[contentLength];
int length =;
// Clean up.
definition = new String(raw, 0, length);
finally {
try {
if (in != null) in.close();
if (hc != null) hc.close();
catch (IOException ignored) {}
return definition;

Put date and time in a application

public class clsTimer
public clsTimer(JLabel sLabel, int sSeconds)
timer = new Timer();
timer.scheduleAtFixedRate(new clsTime(sLabel), 0, sSeconds * 1000);

public class clsTime extends TimerTask
JLabel sLabel = new JLabel();
boolean visible = false;

clsTime(JLabel sLabel){this.sLabel = sLabel; }

public void run()
cal = Calendar.getInstance();
date = cal.getTime();
dateFormatter = DateFormat.getTimeInstance();
sLabel.setText("Today is: " + DateFormat.getDateInstance().format(date) + " [ " + dateFormatter.format(date) + " ] ");

Date date;
Timer timer;
Calendar cal;
DateFormat dateFormatter;

Pass the reference of the java label object in constructor parameter.