Wednesday, August 27, 2008
Java: Distinct List Function
For example:
If input = A,A,B,B,C
This function will return A,B,C in Vector type.
Vector DistinctList(String lists){
int a=0;
int i=0,j=0,k=0;
boolean dup = false;
Vector vPreConCols = new Vector();
String[] L1 = split(lists,","); vPreConCols.add(L1[0]);
a=1;
for(i=1; i<L1.length; i++){
j=0;
while((j<a)&&(dup==false)){
if(L1[i].equalsIgnoreCase(vPreConCols.get(j).toString())){
dup=true;
}
j+=1;
}
if(!dup){
vPreConCols.add(L1[i]);
a+=1;
}
}
return vPreConCols;
}
Thursday, August 21, 2008
Jsp: Set Browser Expired Time
session.setMaxInactiveInterval(int intSecond);
intSecond -> time in second
Example:
session.setMaxInactiveInterval(10);
Description:
The browser will expire within 10 seconds
Sunday, August 17, 2008
Java: Increase Heap Size to prevent java.lang.OutOfMemoryError
* By default the maximum heap size = 128 mb
Sunday, August 10, 2008
Java: Redirect Java Output to a File
In order to redirect the java standard output to a file, we need to use the greater-than-sign (>) character followed by a filename after java.exe on a command line.
For example:
java Hello > D:\output.txt
This will redirect the output of System.out.println() to output.txt file
Saturday, August 9, 2008
Java: Get Current Directory
public class CurrentDir {
public static void main (String args[]) {
File dir1 = new File (".");
File dir2 = new File ("..");
try {
System.out.println ("Current dir : " + dir1.getCanonicalPath());
System.out.println ("Parent dir : " + dir2.getCanonicalPath());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Java: Rename a file
public class ListFile {
public static void main(String args[]){
ListFile lstFile = new ListFile();
System.out.println(lstFile.renameFile("D:/test/nasatest.txt"));
}
public boolean renameFile(String file){
File oldFile = new File(file);
File newFile = new File("D:/test/nasa.txt");
boolean success = false;
// Rename file (or directory)
try{
success = oldFile.renameTo(newFile);
}catch(Exception e){
e.printStackTrace();
}
return success;
}
}
Saturday, August 2, 2008
Java: Download files from HTTP
import java.net.*;
/*
* Command line program to download data from URLs and save
* it to local files. Run like this:
* java FileDownload http://schmidt.devlib.org/java/file-download.html
* @author Marco Schmidt
*/
public class FileDownload {
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(
new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
}
}
}
public static void download(String address) {
int lastSlashIndex = address.lastIndexOf('/');
if (lastSlashIndex >= 0 &&
lastSlashIndex < address.length() - 1) {
download(address, address.substring(lastSlashIndex + 1));
} else {
System.err.println("Could not figure out local file name for " +
address);
}
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
download(args[i]);
}
}
}
Reference: http://schmidt.devlib.org
Java: Delete files in a directory
java.io.File file = new java.io.File("d:\\test");
java.io.File[] f = file.listFiles();
for (int i = 0; i < f.length; i++) {
f[i].delete();
}
}
Sunday, July 27, 2008
Java: Date Format
import java.text.SimpleDateFormat;
java.util.Date today = new java.util.Date();
SimpleDateFormat sdfOutput = new SimpleDateFormat ( "yyyyMMdd" );
String strToday = sdfOutput.format( today );
Date and Time Patterns as below:
Letter: G
Date or Time Component: Era designator
Presentation: Text
Examples: AD
Letter: y
Date or Time Component: Year
Presentation: Year
Examples: 1996; 96
Letter: M
Date or Time Component: Month in year
Presentation: Month
Examples: July; Jul; 07
Letter: w
Date or Time Component: Week in year
Presentation: Number
Examples: 27
Letter: W
Date or Time Component: Week in month
Presentation: Number
Examples: 2
Letter: D
Date or Time Component: Day in year
Presentation: Number
Examples: 189
Letter: d
Date or Time Component: Day in month
Presentation: Number
Examples: 10
Letter: F
Date or Time Component: Day of week in month
Presentation: Number
Examples: 2
Letter: E
Date or Time Component: Day in week
Presentation: Text
Examples: Tuesday; Tue
Letter: a
Date or Time Component: Am/pm marker
Presentation: Text
Examples: PM
Letter: H
Date or Time Component: Hour in day (0-23)
Presentation: Number
Examples: 0
Letter: k
Date or Time Component: Hour in day (1-24)
Presentation: Number
Examples: 24
Letter: K
Date or Time Component: Hour in am/pm (0-11)
Presentation: Number
Examples: 0
Letter: h
Date or Time Component: Hour in am/pm (1-12)
Presentation: Number
Examples: 12
Letter: m
Date or Time Component: Minute in hour
Presentation: Number
Examples: 30
Letter: s
Date or Time Component: Second in minute
Presentation: Number
Examples: 55
Letter: S
Date or Time Component: Millisecond
Presentation: Number
Examples: 978
Letter: z
Date or Time Component: Time zone
Presentation: General time zone
Examples: Pacific Standard Time; PST; GMT-08:00
Letter: Z
Date or Time Component: Time zone
Presentation: RFC 822 time zone
Examples: -0800
Examples
Date and Time Pattern: "yyyy.MM.dd G 'at' HH:mm:ss z"
Result: 2001.07.04 AD at 12:08:56 PDT
Date and Time Pattern: "yyyy.MM.dd G 'at' HH:mm:ss z"
Result: Wed, Jul 4, '01
Date and Time Pattern: "h:mm a"
Result: 12:08 PM
Date and Time Pattern: "hh 'o''clock' a, zzzz"
Result: 12 o'clock PM, Pacific Daylight Time
Date and Time Pattern: "K:mm a, z"
Result: 0:08 PM, PDT
Date and Time Pattern: "yyyyy.MMMMM.dd GGG hh:mm aaa"
Result: 02001.July.04 AD 12:08 PM
Date and Time Pattern: "EEE, d MMM yyyy HH:mm:ss Z"
Result: Wed, 4 Jul 2001 12:08:56 -0700
Date and Time Pattern: "yyMMddHHmmssZ"
Result: 010704120856-0700
Date and Time Pattern: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Result: 2001-07-04T12:08:56.235-0700
Saturday, July 26, 2008
Java: Compare 2 dates
public class CompareDate {
public static void main(String[] args) {
Date dt2 = new Date("7/26/2004");
Date dt3 = new Date("7/25/2004");
if (dt2.compareTo(dt3) > 0) {
System.out.println("dt2>dt3");
} else {
System.out.println("dt3<=dt2");
}
}
}
Java: Check server response
try
{
java.net.Socket s = new Socket();
s.connect(new InetSocketAddress("192.168.0.157", 7777), 1000);
s.close();
System.out.println("Success");
}catch (Exception ex){
System.out.println("Error : " + ex.getMessage());
// failed
// do redirect
}
Java Version 1.3
try{
java.net.Socket s = new Socket(host, port);
s.close();
}catch (Exception ex){
// failed
// do redirect
}
Java: Cast ArrayList to Array
public class CastAryListToArray {
public static void main(String arg[]){
//How to cast ArrayList to Array
//The following code will store arraylist value into array:
ArrayList al = new ArrayList();
al.add("a");
al.add("b");
al.add("c");
String XAxisValue[] = new String[al.size()];
al.toArray(XAxisValue);
for(int i=0;i<XAxisValue.length;i++){
System.out.println("XAxisValue["+i+"] = " + XAxisValue[i]);
}
}
}
Java: Call an Oracle Stored Procedure
* This sample shows how to call a PL/SQL stored procedure using the SQL92
* syntax.
*/
import java.sql.*;
import java.io.*;
class PLSQLExample {
public static void main(String args[]) throws SQLException, IOException {
// Load the driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to the database
// You can put a database name after the @ sign in the connection URL.
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.157:1521:mydb",
"scott", "tiger");
// Create a statement
Statement stmt = conn.createStatement();
// Create the stored function
stmt.execute("create or replace function RAISESAL (name CHAR, raise NUMBER)return
NUMBER is begin return raise + 100000; end;");
// Close the statement
stmt.close();
// Prepare to call the stored procedure RAISESAL.
// This sample uses the SQL92 syntax
CallableStatement cstmt = conn.prepareCall("{? = call RAISESAL (?, ?)}");
// Declare that the first ? is a return value of type Int
cstmt.registerOutParameter(1, Types.INTEGER);
// We want to raise LESLIE's salary by 20,000
cstmt.setString(2, "LESLIE");
// The name argument is the second ?
cstmt.setInt(3, 20000);
// The raise argument is the third ?
// Do the raise
cstmt.execute();
// Get the new salary back
int new_salary = cstmt.getInt(1);
System.out.println("The new salary is: " + new_salary);
// Close the statement
cstmt.close();
// Close the connection
conn.close();
}
}
Java: 2D Array Declaration
int array1[][] = new int [2][2];
//2D Array assignment
array1[0][0] = 1;
array1[0][1] = 2;
array1[1][0] = 3;
array1[1][1] = 4;
//Print 2D Array
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
System.out.println(array1[i][j]);
}
}
Since 26 July 2008: