JAVA-MANI.BLOGSPOT.COM
Saturday, August 30, 2008
This example demonstrate how we do regular expression in Java. The regular expression classes is in the java.uti.regex package. The main class including the java.util.regex.Pattern class and the java.util.regex.Matcher class.

In this example we are only testing to match a string literal if it is exists in the following sentence, we are searching the word lazy.

package org.kodejava.example.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
public static void main(String[] args) {
/*
* To create a Pattern instance we must call the static method called compile()
* in the Pattern class. Pattern object is the compiled representation of a regular
* expression.
*/
Pattern pattern = Pattern.compile("lazy");

/*
* The Matcher class also don't have the public constructor so to create a matcher
* class the Patter's class matcher() method. The Matcher object it self is the engine
* that match the input string against the provided pattern.
*/
Matcher matcher = pattern.matcher("The quick brown fox jumps over the lazy dog");

while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}
Thursday, August 28, 2008
In this example you'll see how we can create a small search and replace program using the regular expression classes in Java. The code below will replace all the brown word and change the color to red.

package org.kodejava.example.regex;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class StringReplace {
public static void main(String[] args) {
String source = "The quick brown fox jumps over the brown lazy dog.";
String find = "brown";
String replace = "red";

//
// Compiles the given regular expression into a pattern
//
Pattern pattern = Pattern.compile(find);

//
// Creates a matcher that will match the given input against the pattern
//
Matcher matcher = pattern.matcher(source);

//
// Replaces every subsequence of the input sequence that matches the
// pattern with the given replacement string
//
String output = matcher.replaceAll(replace);

System.out.println("Source = " + source);
System.out.println("Output = " + output);
}
}
Tuesday, August 26, 2008
This example uses the java.util.regex.Pattern class's split() method to split-up input string separated by commas or whitespaces.

package org.kodejava.example.regex;

import java.util.regex.Pattern;

public class RegexSplitExample {
public static void main(String[] args) {
//
// Pattern for finding commas, whitespaces (space, tabs, new line,
// carriage return, form feed).
//
String pattern = "[,\\s]+";
String colours = "Red,White, Blue Green Yellow, Orange";

Pattern splitter = Pattern.compile(pattern);
String[] result = splitter.split(colours);

for (String colour : result) {
System.out.println("Colour = \"" + colour + "\"");
}
}
}
Sunday, August 24, 2008
package org.kodejava.sample.java.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ZipFileSample
{
public static void main(String[] args)
{
try
{
// Create an instance of ZipFile to read a zip file
// called sample.zip
ZipFile zip = new ZipFile(new File("sample.zip"));

// Here we start to iterate each entries inside
// sample.zip
for (Enumeration e = zip.entries(); e.hasMoreElements();)
{
// Get ZipEntry which is a file or a directory
ZipEntry entry = (ZipEntry) e.nextElement();
// Get some information about the entry such as
// file name, its size.
System.out.println("File name: " + entry.getName()
+ "; size: " + entry.getSize()
+ "; compressed size: "
+ entry.getCompressedSize());

// Now we want to get the content of this entry.
// Get the InputStream, we read through the input
// stream until all the content is read.
InputStream is = zip.getInputStream(entry);
InputStreamReader isr = new InputStreamReader(is);

char[] buffer = new char[1024];
while (isr.read(buffer, 0, buffer.length) != -1)
{
String s = new String(buffer);
// Here we just print out what is inside the
// buffer.
System.out.println(s.trim());
}
}
} catch (ZipException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Friday, August 22, 2008
package org.kodejava.example.util.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingFileExample {
public static void main(String[] args) {
try {
String source = "text.txt";
String target = "example.zip";

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));
FileInputStream fis = new FileInputStream(source);

// put a new ZipEntry in the ZipOutputStream
zos.putNextEntry(new ZipEntry(source));

int size = 0;
byte[] buffer = new byte[1024];

// read data to the end of the source file and write it to the zip
// output stream.
while ((size = fis.read(buffer)) > 0) {
zos.write(buffer);
}

zos.closeEntry();
fis.close();

// Finish zip process
zos.close();


} catch (IOException e) {
e.printStackTrace();
}
}
}
Wednesday, August 20, 2008
You are creating a user management system that will keep user profile and their credential or password. For security reason you'll need to protect the password, to do this you can use the MessageDigest provided by Java API to encrypt the password. The code example below show you a example how to use it.

package org.kodejava.example.security;

import java.security.MessageDigest;

public class EncryptExample {
public static void main(String[] args) {
String password = "secret";
String algorithm = "SHA";

byte[] plainText = password.getBytes();

MessageDigest md = null;

try {
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
e.printStackTrace();
}

md.reset();
md.update(plainText);
byte[] encodedPassword = md.digest();

StringBuilder sb = new StringBuilder();
for (int i = 0; i < encodedPassword.length; i++) {
if ((encodedPassword[i] & 0xff) < 0x10) {
sb.append("0");
}

sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
}

System.out.println("Plain : " + password);
System.out.println("Encrypted: " + sb.toString());
}
}







Here is the example of our encrypted password:

Plain : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4
Monday, August 18, 2008
When you decided to start to learn Java Programming you can start by downloading the Java Development Kit (JDK) from Java Offcial website. They are three different type of JDK, the JSE (Java Standard Edition), JEE (Java Enterprise Edition), JME (Java Mobile Edition).

From the website you can also download the Java API documentations which will sure be your first companion when learning the language. It is better also to download the Java Tutorial Series that was written by the Java expert.

From the tutorial you can learn from the basic of Java programming, the introduction of the fundamental object oriented programming (OOP) which is Java all about. Next you can also find trails in each subject of the API (application programming interface) that is provided by Java, such as the core package, how to communicate with database, Java GUI programming, Image manipulation, RMI, Java Beans Framework, etc.

When you want to write a code you might wonder what editor or IDE that you'll need to use to start learning. A good text editor that support a coloring will be a good candidate, colorful screen is better that just black and white isn't it?

There are a lot of good text editor available today such as the VIM, NotePad++, TextPad, Editplus, UltraEdit. If you already have your prefered editor you can use it of course.

If you'll ready for the big stuff, a bigger homework of project you might considering to use an IDE (Integrated Development Environment) as you'll be working with lots of Java classes and other configuration files and build script for examples. There are many great IDE on the Java world from the free to the commercial product.

What IDE to use is really a developer decision, use whatever tools that can help you to improve your learning and coding activity. You can find IDE such as NetBeans, Eclipse, JCreator, IDEA, JDeveloper, etc.

Beside learning from the Java tutorials there are also many forum on the internet where you can discuss your doubts or your problems. Form like JavaRanch, Java Forum is a great forum with Java gurus that can help you to clarify your doubts and help you to solve your problem. But remember one thing when you ask for help, be polite, elaborate your problem clearly.

A good Java books on your desktop is also a good resource to study Java, from a good books you can learn the bolts and nuts of the Java programming languages. When you have all your arsenal you can get the best out of you in learning Java. Have fun!
Thursday, August 14, 2008
In this example we create a small program to send email with a file attachment. To send message with attachment we need to create an email with javax.mail.Multipart object which basically will contains the email text message and then add a file to the second block, which both of them is an object of javax.mail.internet.MimeBodyPart. In this example we also use the javax.activation.FileDataSource.

package org.kodejava.example.mail;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailAttachmentDemo {
public static void main(String[] args) {
EmailAttachmentDemo demo = new EmailAttachmentDemo();
demo.sendEmail();
}

public void sendEmail() {
String from = "me@localhost";
String to = "me@localhost";
String subject = "Important Message";
String bodyText = "This is a important message with attachment";
String filename = "message.pdf";

Properties properties = new Properties();
properties.put("mail.stmp.host", "localhost");
properties.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(properties, null);

try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setSentDate(new Date());

//
// Set the email message text.
//
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(bodyText);

//
// Set the email attachment file
//
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(filename) {
@Override
public String getContentType() {
return "application/octet-stream";
}
};
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(filename);

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);

message.setContent(multipart);

Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Tuesday, August 12, 2008
Using for..each like command to iterate arrays or a list can be much simplified our code. Below is an example how to do it in Java, the first loop is for iterating array and the second for iterating a list containing a some names.


package org.kodejava.example.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
public static void main(String[] args) {
Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

for (Integer i : numbers) {
System.out.println("Number: " + i);
}

List names = new ArrayList();
names.add("James");
names.add("Joshua");
names.add("Scott");

for (String name : names) {
System.out.println("Name: " + name);
}
}
}
Sunday, August 10, 2008
Autoboxing is a new feature offered in the Tiger (1.5) release of Java SDK. In short auto boxing is a capability to convert or cast between object wrapper and it's primitive type.

Previously when placing a primitive data into one of the Java Collection Framework we have to wrap it to an object because the collection cannot work with primitive data. Also when calling a method that requires an instance of object than an int or long, than we have to convert it too.

But now, starting from version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explisit object casting.

Here an example how it will look like using the Autoboxing feature:


public static void main(String[] args)
{
Map map = new HashMap();

// Here we put an int into the Map, and it accepted
// as it will be autoboxed or converted into the wrapper
// of this type, in this case the Integer object.
map.put("Age", 25);

// Here we can just get the value from the map, no need
// to cast it from Integer to int.
int age = map.get("Age");

// Here we simply do the math on the primitive type
// and got the result as an Integer.
Integer newAge = age + 10;
}
Friday, August 8, 2008
Here is an example code to create a text file an put some contents in it. This program will create a file called write.txt.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.Writer;
import java.io.FileNotFoundException;
import java.io.IOException;

public class WriteTextFileExample
{
public static void main(String[] args)
{
Writer writer = null;

try
{
String text = "This is a text file";

File file = new File("write.txt");
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (writer != null)
{
writer.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Thursday, August 7, 2008
While moving through the result set you might want to know in what row is the current cursor positioned. To get this information you can call the ResultSet's getRow() method.

package org.kodejava.example.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ScrollableGetRowExample {
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery("SELECT * FROM products");
while (resultSet.next()) {
String productCode = resultSet.getString("product_code");

//
// By calling the getRow() method of the result set we know what is the
// current row in the result set that we are reading the data from.
//
int row = resultSet.getRow();

System.out.println(row + ". " + productCode);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
}
}

SUBSCRIBE VIA eMAIL

Enter your email address:

Delivered by FeedBurner

Recent Posts

Firefox 3

Counter

internet companies

Live Traffic Map

Subscribe Now