Thursday, July 31, 2008
package org.kodejava.example.io;
public class CurrentDirectoryExample
{
public static void main(String[] args) {
//
// System property key to get current working directory.
//
String USER_DIR_KEY = "user.dir";
String userHomeDir = System.getProperty(USER_DIR_KEY);
System.out.println("Working Directory: " + userHomeDir);
}
}
public class CurrentDirectoryExample
{
public static void main(String[] args) {
//
// System property key to get current working directory.
//
String USER_DIR_KEY = "user.dir";
String userHomeDir = System.getProperty(USER_DIR_KEY);
System.out.println("Working Directory: " + userHomeDir);
}
}
Wednesday, July 30, 2008
Here you'll find how to convert string into InputStream object using ByteArrayInputStream class.
package org.kodejava.example.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringToStream {
public static void main(String[] args) {
String text = "Converting String to InputStream Example";
/*
* Convert String to InputString using ByteArrayInputStream class.
* This class constructor takes the string byte array which can be
* done by calling the getBytes() method.
*/
try {
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringToStream {
public static void main(String[] args) {
String text = "Converting String to InputStream Example";
/*
* Convert String to InputString using ByteArrayInputStream class.
* This class constructor takes the string byte array which can be
* done by calling the getBytes() method.
*/
try {
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Tuesday, July 29, 2008
This example will show you how to convert an InputStream to String. In the code snippet below we read a data.txt file, could be from common folder or from inside a jar file
package org.kodejava.example.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class StreamToString {
public static void main(String[] args) {
StreamToString sts = new StreamToString();
/*
* Get input stream of our data file. This file can be in the root of
* you application folder or inside a jar file if the program is packed
* as a jar.
*/
InputStream is = sts.getClass().getResourceAsStream("/data.txt");
/*
* Call the method to convert the stream to string
*/
System.out.println(sts.convertStreamToString(is));
}
public String convertStreamToString(InputStream is) {
/*
* To conver the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
package org.kodejava.example.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class StreamToString {
public static void main(String[] args) {
StreamToString sts = new StreamToString();
/*
* Get input stream of our data file. This file can be in the root of
* you application folder or inside a jar file if the program is packed
* as a jar.
*/
InputStream is = sts.getClass().getResourceAsStream("/data.txt");
/*
* Call the method to convert the stream to string
*/
System.out.println(sts.convertStreamToString(is));
}
public String convertStreamToString(InputStream is) {
/*
* To conver the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Monday, July 28, 2008
import java.util.StringTokenizer;
public class StringTokenizerSample
{
public static void main(String[] args)
{
StringTokenizer st =
new StringTokenizer("a stringtokenizer sample");
// get how many tokens inside st object
System.out.println("tokens count: " + st.countTokens());
// iterate st object to get more tokens from it
while (st.hasMoreElements())
{
String token = st.nextElement().toString();
System.out.println("token = " + token);
}
// split a date string using a forward slash as
// delimiter
st = new StringTokenizer("2005/12/15", "/");
while (st.hasMoreElements())
{
String token = st.nextToken();
System.out.println("token = " + token);
}
}
}
The above code is an example of using StringTokenizer to split a string. In the current JDK this class is discourageg to be used, using instead the String.split(...) method or using a new java.util.regex package.
Here is the result of this sample code:
tokens count: 3
token = a
token = stringtokenizer
token = sample
token = 2005
token = 12
token = 15
public class StringTokenizerSample
{
public static void main(String[] args)
{
StringTokenizer st =
new StringTokenizer("a stringtokenizer sample");
// get how many tokens inside st object
System.out.println("tokens count: " + st.countTokens());
// iterate st object to get more tokens from it
while (st.hasMoreElements())
{
String token = st.nextElement().toString();
System.out.println("token = " + token);
}
// split a date string using a forward slash as
// delimiter
st = new StringTokenizer("2005/12/15", "/");
while (st.hasMoreElements())
{
String token = st.nextToken();
System.out.println("token = " + token);
}
}
}
The above code is an example of using StringTokenizer to split a string. In the current JDK this class is discourageg to be used, using instead the String.split(...) method or using a new java.util.regex package.
Here is the result of this sample code:
tokens count: 3
token = a
token = stringtokenizer
token = sample
token = 2005
token = 12
token = 15
Sunday, July 27, 2008
StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these condition is true that the string considered blank.
There's also a StringUtils.isEmpty(), only these method doesn't not check for whitespaces only string. For checking the oposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().
Using this methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy method.
package org.kodejava.example.commons.lang;
import org.apache.commons.lang.StringUtils;
public class CheckEmptyString {
public static void main(String[] args) {
String var1 = null;
String var2 = "";
String var3 = " \t\t\t";
String var4 = "Hello World";
System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));
System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));
System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
}
}
How do I check for an empty string?
Bookmark this example!
Category: Commons Lang, viewed: 2858 time(s).
StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these condition is true that the string considered blank.
There's also a StringUtils.isEmpty(), only these method doesn't not check for whitespaces only string. For checking the oposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().
Using this methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy method.
package org.kodejava.example.commons.lang;
import org.apache.commons.lang.StringUtils;
public class CheckEmptyString {
public static void main(String[] args) {
String var1 = null;
String var2 = "";
String var3 = " \t\t\t";
String var4 = "Hello World";
System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));
System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));
System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
}
}
The result of our program are:
var1 is blank? = true
var2 is blank? = true
var3 is blank? = true
var4 is blank? = false
var1 is not blank? = false
var2 is not blank? = false
var3 is not blank? = false
var4 is not blank? = true
var1 is empty? = true
var2 is empty? = true
var3 is empty? = false
var4 is empty? = false
var1 is not empty? = false
var2 is not empty? = false
var3 is not empty? = true
var4 is not empty? = true
There's also a StringUtils.isEmpty(), only these method doesn't not check for whitespaces only string. For checking the oposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().
Using this methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy method.
package org.kodejava.example.commons.lang;
import org.apache.commons.lang.StringUtils;
public class CheckEmptyString {
public static void main(String[] args) {
String var1 = null;
String var2 = "";
String var3 = " \t\t\t";
String var4 = "Hello World";
System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));
System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));
System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
}
}
How do I check for an empty string?
Bookmark this example!
Category: Commons Lang, viewed: 2858 time(s).
StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these condition is true that the string considered blank.
There's also a StringUtils.isEmpty(), only these method doesn't not check for whitespaces only string. For checking the oposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().
Using this methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy method.
package org.kodejava.example.commons.lang;
import org.apache.commons.lang.StringUtils;
public class CheckEmptyString {
public static void main(String[] args) {
String var1 = null;
String var2 = "";
String var3 = " \t\t\t";
String var4 = "Hello World";
System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));
System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));
System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
}
}
The result of our program are:
var1 is blank? = true
var2 is blank? = true
var3 is blank? = true
var4 is blank? = false
var1 is not blank? = false
var2 is not blank? = false
var3 is not blank? = false
var4 is not blank? = true
var1 is empty? = true
var2 is empty? = true
var3 is empty? = false
var4 is empty? = false
var1 is not empty? = false
var2 is not empty? = false
var3 is not empty? = true
var4 is not empty? = true
Saturday, July 26, 2008
package org.kodejava.example.java.util;
import java.util.Calendar;
public class DateDifferentExample
{
public static void main(String[] args)
{
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, 12, 30);
cal2.set(2007, 05, 03);
// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}
Here is the result:
In milliseconds: 10713600000 milliseconds.
In seconds: 10713600 seconds.
In minutes: 178560 minutes.
In hours: 2976 hours.
In days: 124 days.
import java.util.Calendar;
public class DateDifferentExample
{
public static void main(String[] args)
{
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, 12, 30);
cal2.set(2007, 05, 03);
// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}
Here is the result:
In milliseconds: 10713600000 milliseconds.
In seconds: 10713600 seconds.
In minutes: 178560 minutes.
In hours: 2976 hours.
In days: 124 days.
Friday, July 25, 2008
In this example we'll use the StringUtils.substringBetween() method. Here we'll extract the title and body of our HTML document. Let's see the code.
package org.kodejava.example.commons.lang;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
public class NestedString {
public static void main(String[] args) {
String helloHtml = "" +
"" +
"Hello World from Java " +
"" +
"Hello, today is: " + new Date() +
"" +
"";
String title = StringUtils.substringBetween(helloHtml, "", " ");
String content = StringUtils.substringBetween(helloHtml, "", "");
System.out.println("title = " + title);
System.out.println("content = " + content);
}
}
package org.kodejava.example.commons.lang;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
public class NestedString {
public static void main(String[] args) {
String helloHtml = "" +
"" +
"
"" +
"Hello, today is: " + new Date() +
"" +
"";
String title = StringUtils.substringBetween(helloHtml, "
String content = StringUtils.substringBetween(helloHtml, "", "");
System.out.println("title = " + title);
System.out.println("content = " + content);
}
}
Monday, July 21, 2008
sort array values in descending order
Here you'll find an example how to sort array's values and sort it in ascending or descending order.
package org.kodejava.example.util;
import java.util.Arrays;
import java.util.Collections;
public class SortArrayWithOrder {
public static void main(String[] args) {
Integer[] points = new Integer[5];
points[0] = 94;
points[1] = 53;
points[2] = 70;
points[3] = 44;
points[4] = 64;
//
// Sort the points array, the default order is in ascending order.
// [44, 53, 64, 70, 94]
//
Arrays.sort(points);
System.out.println(Arrays.toString(points));
//
// Sort the points array in descending order.
// [94, 70, 64, 53, 44]
//
Arrays.sort(points, Collections.reverseOrder());
System.out.println(Arrays.toString(points));
}
}
Sunday, July 20, 2008
sort array values in case insensitive order
By default the when sorting an arrays the value will be ordered in case-sensitive order. This example show you how to order it in case-insensitive order.package org.kodejava.example.util;
import java.util.Arrays;
import java.util.Collections;
public class SortArrayCaseSensitivity {
public static void main(String[] args) {
String[] teams = new String[5];
teams[0] = "Manchester United";
teams[1] = "chelsea";
teams[2] = "Arsenal";
teams[3] = "liverpool";
teams[4] = "EVERTON";
//
// Sort array, by default it will be sort in case sensitive order.
// [Arsenal, EVERTON, Manchester United, chelsea, liverpool]
//
Arrays.sort(teams);
System.out.println(Arrays.toString(teams));
//
// Sort array in case insensitive order
// [Arsenal, chelsea, EVERTON, liverpool, Manchester United]
//
Arrays.sort(teams, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(teams));
}
}
Saturday, July 19, 2008
This example shows you how we can sort items of an ArrayList using the Collections.sort() methods. Beside accepting the list object to be sorted we can also pass a Comparator implementation to define the sorting behavior.
package org.kodejava.example.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List colours = new ArrayList();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
Collections.sort(colours, Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
}
The code will output:
[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]
package org.kodejava.example.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List colours = new ArrayList();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
Collections.sort(colours, Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
}
The code will output:
[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]
Tuesday, July 15, 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();
}
}
}
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();
}
}
}
Monday, July 14, 2008
An example for obtaining a connection to MySQL database. For connecting to other database all you have to do is change the url to match to url format for a particular database and of course you have to register a correct JDBC driver of the database you are using.
package org.kodejava.sample.java.sql;
import java.sql.DriverManager;
import java.sql.Connection;
public class ConnectionSample
{
// Below is the format of jdbc url for MySql database.
public static final String URL =
"jdbc:mysql://localhost/testdb";
// The username for connecting to the database
public static final String USERNAME = "root";
// The password for connecting to the database
public static final String PASSWORD = "";
public static void main(String[] args) throws Exception
{
Connection connection = null;
try
{
// Register a database jdbc driver to be used by
// our program. In this example I choose a MySQL
// driver.
Class.forName("com.mysql.jdbc.Driver");
// Get the connection object from the driver manager
// by passing the url of our database, username and
// the password.
connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
// Do what ever you want to do with the connection
// object, such as reading some records from database,
// updating or deleting a row. But don't for get the
// close the connection right after you've finished
// using it.
} finally
{
if (connection != null)
{
connection.close();
}
}
}
}
package org.kodejava.sample.java.sql;
import java.sql.DriverManager;
import java.sql.Connection;
public class ConnectionSample
{
// Below is the format of jdbc url for MySql database.
public static final String URL =
"jdbc:mysql://localhost/testdb";
// The username for connecting to the database
public static final String USERNAME = "root";
// The password for connecting to the database
public static final String PASSWORD = "";
public static void main(String[] args) throws Exception
{
Connection connection = null;
try
{
// Register a database jdbc driver to be used by
// our program. In this example I choose a MySQL
// driver.
Class.forName("com.mysql.jdbc.Driver");
// Get the connection object from the driver manager
// by passing the url of our database, username and
// the password.
connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
// Do what ever you want to do with the connection
// object, such as reading some records from database,
// updating or deleting a row. But don't for get the
// close the connection right after you've finished
// using it.
} finally
{
if (connection != null)
{
connection.close();
}
}
}
}
Sunday, July 13, 2008
Here you'll find how to convert string into InputStream object using ByteArrayInputStream class.
package org.kodejava.example.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringToStream {
public static void main(String[] args) {
String text = "Converting String to InputStream Example";
/*
* Convert String to InputString using ByteArrayInputStream class.
* This class constructor takes the string byte array which can be
* done by calling the getBytes() method.
*/
try {
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringToStream {
public static void main(String[] args) {
String text = "Converting String to InputStream Example";
/*
* Convert String to InputString using ByteArrayInputStream class.
* This class constructor takes the string byte array which can be
* done by calling the getBytes() method.
*/
try {
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Thursday, July 10, 2008
The following code shows how we can convert a string representation of date into java.util.Date object.
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
package org.kodejava.example.java.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
How do I convert String to Date object?
Bookmark this example!
Category: java.text, viewed: 32696 time(s).
The following code shows how we can convert a string representation of date into java.util.Date object.
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
package org.kodejava.example.java.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
And here is the result of our code:
Today = 20/12/2005
The example starts by creating an instance of SimpleDateFormat with "dd/MM/yyyy" format which mean that the date string is formatted in day-month-year sequence.
Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.
Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.
Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
package org.kodejava.example.java.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
How do I convert String to Date object?
Bookmark this example!
Category: java.text, viewed: 32696 time(s).
The following code shows how we can convert a string representation of date into java.util.Date object.
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
package org.kodejava.example.java.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
And here is the result of our code:
Today = 20/12/2005
The example starts by creating an instance of SimpleDateFormat with "dd/MM/yyyy" format which mean that the date string is formatted in day-month-year sequence.
Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.
Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.
Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
Wednesday, July 9, 2008
import java.io.File;
import org.apache.commons.io.FileUtils;
public class DirectorySizeSample
{
public static void main(String[] args)
{
// Using FileUtils.sizeOfDirectory() we can calculate
// the size of a directory including it sub directory
long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
System.out.println("Size: " + size + " bytes");
}
}
import org.apache.commons.io.FileUtils;
public class DirectorySizeSample
{
public static void main(String[] args)
{
// Using FileUtils.sizeOfDirectory() we can calculate
// the size of a directory including it sub directory
long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
System.out.println("Size: " + size + " bytes");
}
}
Saturday, July 5, 2008
To rotate things, we need to convert polar to cartesian coordinates:
x = r * Math.cos(theta); and y = r * Math.sin(theta);
Polar coordinates (r, theta) are just another way of specifying points in a 2D plane, where r represents the distance of a point from the center and theta the angle from the horizontal axis (x-axis) through the center. The following applet shows this principle in a minimized form, it rotates a hand around the center and displays the angle accordingly.
//Sourcecode
x = r * Math.cos(theta); and y = r * Math.sin(theta);
Polar coordinates (r, theta) are just another way of specifying points in a 2D plane, where r represents the distance of a point from the center and theta the angle from the horizontal axis (x-axis) through the center. The following applet shows this principle in a minimized form, it rotates a hand around the center and displays the angle accordingly.
//Sourcecode
import java.awt.*;
import java.applet.*;
public class Project40 extends Applet implements Runnable
{
Thread runner;
Image Buffer;
Graphics gBuffer;
int angle;
public void init()
{
//create graphics buffer, the size of the applet
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}
public void run()
{
while(true)
{
try {runner.sleep(250);}
catch (Exception e) { }
repaint();
}
}
void drawStuff()
{
//paint background black
gBuffer.setColor(Color.black);
gBuffer.fillRect(0,0,size().width,size().height);
//get the center of the applet
Point p=new Point(size().width/2, size().height/2);
//define the hand length
int LENGTH=70;
//calculate the vector, using the constant Pi
double vector = angle * Math.PI*2 / 360.0;
int vx=(int)(p.x+LENGTH*Math.sin(vector));
int vy=(int)(p.y-LENGTH*Math.cos(vector));
gBuffer.setColor(Color.yellow);
//the hand
gBuffer.drawLine(p.x, p.y, vx, vy);
//the round "axis"
gBuffer.drawOval(p.x-6,p.y-6,12,12);
//display the angle in degrees
gBuffer.setFont(new Font("Helvetica",Font.PLAIN,13));
gBuffer.drawString("Angle="+angle+"°",10,20);
//increase the angle, to move the hand
if(angle<360)
angle++;
else
angle=0;
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
Friday, July 4, 2008
To conclude this chapter, let's create some funny random words! Some of them will sound familiar, some really are. The algorithm is quite similar to the last applets, but this time we create two String constants, containing vowels and the consonants each. In our method randomWord(), which returns the random string when we call it, we create 3 random characters, each of the vowels and the consonants string. Then we combine these characters in a specific order, to get words without two consonants or vowels in succession. I use one of four algorithms, that are selected at random. To make it more fun to watch, I create only 1 word a second and print them one below the other and shifted to the right, until the window is full. Then the background is repainted and everything starts again.
//Sourcecode
//Sourcecode
import java.awt.*;
import java.applet.*;
public class Project39 extends Applet implements Runnable
{
Thread runner;
Image Buffer;
Graphics gBuffer;
String vowels="aeiouy"; //6 characters
String consonants="bcdfghklmnprstvwz"; //17 characters
int x=10, y=30;
Font font=new Font("Helvetica", Font.PLAIN, 30);
Color bgColor=new Color(0,120,0);
public void init()
{
//create graphics buffer, the size of the applet
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}
public void run()
{
while(true)
{
try {runner.sleep(1000);}
catch (Exception e) { }
repaint();
}
}
String randomWord()
{
int c1=(int)(Math.random()*17);
int c2=(int)(Math.random()*17);
int c3=(int)(Math.random()*17);
String sc1=consonants.substring(c1, c1+1);
String sc2=consonants.substring(c2, c2+1);
String sc3=consonants.substring(c2, c2+1);
int v1=(int)(Math.random()*6);
int v2=(int)(Math.random()*6);
int v3=(int)(Math.random()*6);
String sv1=vowels.substring(v1, v1+1);
String sv2=vowels.substring(v2, v2+1);
String sv3=vowels.substring(v3, v3+1);
//algo 0=cvcvc
//algo 1=cvcvcv
//algo 2=vcvc
//algo 3=vcvcv
String word;
int algo=(int)(Math.random()*4);
switch(algo)
{
case 0: word=sc1+sv1+sc2+sv2+sc3;
break;
case 1: word=sc1+sv1+sc2+sv2+sc3+sv3;
break;
case 2: word=sv1+sc1+sv2+sc2+sv3;
break;
default: word=sv1+sc1+sv2+sc2+sv3+sc3;
}
return word;
}
void drawStuff()
{
//repaint background if window is full
if(y==30)
{
gBuffer.setColor(bgColor);
gBuffer.fillRect(0,0,size().width,size().height);
}
gBuffer.setFont(font);
//pause after the last word
if(y<300) s="randomWord();" color="red">//the drop shadow
gBuffer.setColor(Color.black);
gBuffer.drawString(s,x+2,y+2);
gBuffer.setColor(Color.green);
gBuffer.drawString(s,x,y);
}
y+=36;
x+=25;
if(y>350)
{
y=30;
x=10;
}
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
Thursday, July 3, 2008
Now let's have some real fun with falling letters! We create a class FallingCharacter that represents the falling letters. We create an array of objects of that class (here: 100, represented by the variable MAX, can be changed easily). Each object takes care for random values for the initial position, size, color and speed! The speed is represented by the double precision floating point variable yinc, which is added to the y position in the member method fall(). Only floating point variables guarantee for smooth movement in many different speed values. They are casted to int values only in the paint method, in the end. The constructor of the FallingCharacter class receives the width and height of the applet as parameters, to make it possible to easily change the applet size without changing the code. After reaching the bottom of the window, the letters reappear at the top again.
//Sourcecode
//Sourcecode
import java.awt.*;
import java.applet.*;
class FallingCharacter
{
int fontSize, h;
double x, y, yinc;
String s, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Color color;
Graphics g;
Font font;
public FallingCharacter(int width, int height)
{
h=height;
//random font size 10..50
fontSize=(int)(Math.random()*40)+10;
font=new Font("TimesRoman", Font.PLAIN, fontSize);
//random font color
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
color=new Color(red, green, blue);
//random initial coordinates within the applet bounderies
x=(Math.random()*width);
y=(Math.random()*height);
//random falling speed
yinc=(Math.random()*2.5)+1.0;
//random substring from the alphabet string (one out of 26 characters)
int character=(int)(Math.random()*26);
s=alphabet.substring(character, character+1);
}
public void fall()
{
if(y y+=yinc;
else
y=-fontSize;
}
public void paint(Graphics gr)
{
g=gr;
g.setColor(color);
g.setFont(font);
g.drawString(s,(int)x,(int)y);
}
}
public class Project38 extends Applet implements Runnable
{
Thread runner;
Image Buffer;
Graphics gBuffer;
int i;
static final int MAX=100;
FallingCharacter fc[];
public void init()
{
//create graphics buffer, the size of the applet
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
fc = new FallingCharacter[MAX];
for(i=0;i fc[i] = new FallingCharacter(size().width-30,size().height);
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}
public void run()
{
while(true)
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {runner.sleep(15);}
catch (Exception e) { }
repaint();
}
}
public void drawStuff()
{
gBuffer.setColor(Color.black);
gBuffer.fillRect(0,0,size().width,size().height);
for(i=0;i fc[i].fall();
for(i=0;i fc[i].paint(gBuffer);
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
Wednesday, July 2, 2008
Let's have a little fun with random letters! First, we create a String object alphabet, containing all 26 letters of the alphabet. Then we draw a random number between 0 and 25 and use it as an argument in the String method substring. We pass two integer arguments for the first and the last character of the new substring, so we get a random character. To make it fun to watch, we also randomize the color, size and position of the letter on the screen. After some time, we redraw the background black.
//Sourcecode
//Sourcecode
import java.awt.*;
import java.applet.*;
public class Project37 extends Applet implements Runnable
{
Thread runner;
Image Buffer;
Graphics gBuffer;
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int ticker;
public void init()
{
//create graphics buffer, the size of the applet
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}
public void run()
{
while(true)
{
try {runner.sleep(50);}
catch (Exception e) { }
repaint();
}
}
public void drawStuff()
{
//repaint background after 20 seconds
if(ticker==0)
{
gBuffer.setColor(Color.black);
gBuffer.fillRect(0,0,size().width,size().height);
}
ticker++;
if(ticker>400)
ticker=0;
//random font size 10..50
int fontSize=(int)(Math.random()*40)+10;
//random font color
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
gBuffer.setColor(new Color(red, green, blue));
//random coordinates within the applet bounderies
int x=(int)(Math.random()*size().width);
int y=(int)(Math.random()*size().height);
//random substring from the alphabet string (one out of 26 characters)
int character=(int)(Math.random()*26);
String s=alphabet.substring(character, character+1);
gBuffer.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
gBuffer.drawString(s,x,y);
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
Subscribe to:
Posts (Atom)
SUBSCRIBE VIA eMAIL
Recent Posts
Archives
- December 2008 (5)
- November 2008 (15)
- October 2008 (17)
- September 2008 (9)
- August 2008 (12)
- July 2008 (19)
- June 2008 (22)
- May 2008 (17)
- April 2008 (2)
Categories
- java.sql (19)
- Examples (18)
- INTRODUCTION (9)
- JAVA APPLET (9)
- java.awt (8)
- java.net (8)
- java.beans (7)
- JAVA String Utility (6)
- Arrays (4)
- java.math (3)
- java.util.regex (3)
- Sort (2)
- Swing (2)
- java.security (2)
- java.util.zip (2)
- Catching Exceptions (1)
- Classes and Objects (1)
- Core Java Programs-part 1 (1)
- Core Java Programs-part 2 (1)
- Core Java Programs-part3 (1)
- Criticism of Java programming language (1)
- Falling Letters (1)
- File I/O and Streams (1)
- Fun With Letters and Words (1)
- Get current working directory (1)
- How do I convert String to Date object? (1)
- How do I convert string into InputStream? (1)
- How do i calculate directory size? (1)
- How to make executable jar files in JDK1.3.1? (1)
- Interfaces (1)
- JAVA Date Utility (1)
- Java Arithmetic Operators (1)
- Java Assignment Operators (1)
- Java Boolean Operators (1)
- Java Command Line Arguments (1)
- Java Comments (1)
- Java Conditional Operators (1)
- Java Data and Variables (1)
- Java Hello World Program (1)
- Java If-Else Statement (1)
- Java Increment and Decrement Operators (1)
- Java Loops (while (1)
- Java Relational Operators (1)
- Java Variables and Arithmetic Expressions (1)
- Java Virtual Machine (1)
- Know the current position of cursor (1)
- Letters (1)
- Methods (Includes Recursive Methods) (1)
- Rotating Lines (1)
- Send an email with attachment (1)
- Use for..each in Java (1)
- What is Autoboxing? (1)
- Write text file (1)
- connection to database (1)
- do-while and for loops) (1)

