Thursday, March 22, 2012

How to Create Directory in Java,Directory Creation in Java

0 comments

Java Create Directory - Java Tutorial


In this Tutorial you will learn how to create directory and check whether that directory is exist.If the directory is exist then it will not create otherwise,


import java.io.File;

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com
 */
public class CreateDirectory {

    public static void main(String[] args) {

        String directory = "JAVADIR";
        String directory_tree = "JSUPPORT/JAVA";
        boolean dir_exist = false;

        try {
            // Check whether the derectory is exist
            dir_exist = new File(directory).isDirectory();

            if (dir_exist) {
                System.out.println("directory already created.....");
            } else {
                // creat directory
                new File(directory).mkdir();
            }

            // Check whether the derectory is exist
            dir_exist = new File(directory_tree).isDirectory();

            if (dir_exist) {
                System.out.println("directories already created.....");
            } else {
                // create directories
                new File(directory_tree).mkdirs();
            }

        } catch (Exception e) {
            System.out.println("Error : "+e.getMessage());
        }

    }
}

Read more...

How to Write a File in Java,Java Write to File Example,Write a File in Java

0 comments

Java a Write file  - Java Tutorial

In this Tutorial you will learn how to write a file,It use FileWriter class and BufferedWriter class to write the file.



import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com
 */
public class WriteFile {


    public static void writToFile(String data){

        try {

            // Create a new file  TEST.txt
            FileWriter file_writer  = new FileWriter("TEST.txt");
            BufferedWriter bufferd_writer   =   new BufferedWriter(file_writer);

            // write data to file
            bufferd_writer.write(data);
            // flush and close the file
            bufferd_writer.flush();
            bufferd_writer.close();

        } catch (IOException ex) {
            System.out.println("Cannot write    :" + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        writToFile("Hello Java Sri Lankan Support");
    }
}

Read more...

Wednesday, March 21, 2012

How To Get Date Range in Java Calendar's set() add() and roll()

0 comments

 Calendar (Java 2 Platform SE 5.0) set() add()  and roll() 



import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com
 */

enum DateEnum {
    DAILY,
    WEEKLY,
    MONTHLY;
}

public class DateRange {

    public int x = 2;
    public String date,stdate,endate;

    private String getDateTime(DateEnum type) {

        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date d = c.getTime();
        
        c.setTime(d);

        switch (type) {

            case DAILY:
                c.roll(Calendar.DAY_OF_WEEK, -1);
                date = sdf.format(c.getTime());
                break;
            case WEEKLY:
                 c.roll(Calendar.DAY_OF_WEEK, -1);
                 stdate = sdf.format(c.getTime());
                 c.roll(Calendar.WEEK_OF_MONTH,-1);
                 endate = sdf.format(c.getTime());
                 date = stdate+","+endate;
                break;

            case MONTHLY:
                 c.roll(Calendar.DAY_OF_WEEK, -1);
                 stdate = sdf.format(c.getTime());
                 c.roll(Calendar.MONTH,-1);
                 endate = sdf.format(c.getTime());
                 date = stdate+","+endate;
                break;
        }
        return date;
    }

    public static void main(String[] arr) {

        DateRange dr = new DateRange();

        System.out.println(dr.getDateTime(DateEnum.DAILY));
        System.out.println(dr.getDateTime(DateEnum.WEEKLY));
        System.out.print(dr.getDateTime(DateEnum.MONTHLY));

    }
}

Read more...

Wednesday, March 14, 2012

Insert and Retrieve Values from a Map (HashMap)

0 comments
  • Insert values into HashMap
  • Retrieve values from HashMap

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
*
* @author JSupport
* http://javasrilankansupport.blogspot.com
*
*/

public class InsertRetrieveDataFromMap {

// get values from HashMap
public static void getHashMapData(Map order_details){
Set key_set;

// gat all key to Set
key_set     =   order_details.keySet();

for (Iterator it = key_set.iterator(); it.hasNext();) {

String key      =   (String) it.next();
String  value   =   (String) order_details.get(key);

System.out.println("Map key : "+key +"\tKey Value : "+key);
}

}
public static void main(String[] args) {

HashMap order_details   =   new HashMap();

//     add key value pairs to HashMap

order_details.put("kitchName", "Chinese Kitchen");
order_details.put("waiterName", "Silva");
order_details.put("tableName", "20");

getHashMapData(order_details);
}
}




This program dose answer to following....
  • How to Insert values into HashMap in Java
  • How to Insert values into HashMap in Java
  • How to Retrieve values from HashMap in Java
  • How to Retrieve values from Map in Java
Read more...

Thursday, March 8, 2012

Get Available COM Ports in Java Comm

0 comments
First of all you must properly install Java Comm API.There is nothing much more




package jsupport.com;

import gnu.io.CommPortIdentifier;
import java.util.Enumeration;

/**
 *
 * @author JSupport
 */
public class GetAvailableComPorts {

    public static void getComPorts(){
        String     port_type;
        Enumeration  enu_ports  = CommPortIdentifier.getPortIdentifiers();

        while (enu_ports.hasMoreElements()) {
            CommPortIdentifier port_identifier = (CommPortIdentifier) enu_ports.nextElement();

            switch(port_identifier.getPortType()){
                case CommPortIdentifier.PORT_SERIAL:
                    port_type   =   "Serial";
                    break;
                case CommPortIdentifier.PORT_PARALLEL:
                    port_type   =   "Parallel";
                    break;
                case CommPortIdentifier.PORT_I2C:
                    port_type   =   "I2C";
                    break;
                case CommPortIdentifier.PORT_RAW:
                    port_type   =   "Raw";
                    break;
                case CommPortIdentifier.PORT_RS485:
                    port_type   =   "RS485";
                    break;
                default:
                    port_type   =   "Unknown";
                    break;
            }

            System.out.println("Port : "+port_identifier.getName() +" Port type : "+port_type);
        }
    }
    public static void main(String[] args) {
        getComPorts();
    }
}

Read more...

Tuesday, February 28, 2012

How to Validate Email Address using Java Pattern

8 comments


Validate an email address is easy if you have good valid pattern expression.   

package com.jsupport;

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

/**
 *
 * @author JSupport
 */
public class ValidateEmailAddress {

    public boolean isValidEmailAddress(String emailAddress) {
        
        String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = emailAddress;
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        return matcher.matches();
        
    }

    public static void main(String[] args) {
        
        ValidateEmailAddress vea = new ValidateEmailAddress();

        System.out.println(vea.isValidEmailAddress("info@jsupport.info"));      // Valide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsup@port.info"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsupport.in_fo"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("in@fo@jsupport.info"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsupport.com.lk"));    // Valide emaill address
    }
}


Here you will find how to validate email address using Java Mail API
Read more...

Friday, February 24, 2012

How to Resize Image according to the screen size using Java

0 comments
package jsupport.com;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

/**
 *
 * @author JSupport
 */
public class ResizeImage {

    private  URL url = null;

    public  BufferedImage resize() {
        try {
                url = getClass().getResource("/images/image.jpeg");
                BufferedImage originalImage = ImageIO.read(url);
                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

                int screenWidth = (int) dim.getWidth();
                int screenHeight = (int) dim.getHeight();

                int w = originalImage.getWidth();
                int h = originalImage.getHeight();
                BufferedImage dimg = dimg = new BufferedImage(screenWidth, screenHeight, originalImage.getType());
                Graphics2D g = dimg.createGraphics();
                g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g.drawImage(originalImage, 0, 0, screenWidth, screenHeight, 0, 0, w, h, null);
                g.dispose();

                return dimg;
        }catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Read more...

How To Get Installed Printer name using Java

1 comments
Get Installed printers in Java
  • You can get installed printers by using both javax.print.PrintService and javax.print.PrintServiceLookup 
  • PrintServiceLookup.lookupDefaultPrintService().getName(); will gives default printer name;

package jsupport.com;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

/**
 *
 * @author Jsupport
 */

public class ShowPrinters {

    String defaultPrinter;
    public void SearchPrinter() {
        PrintService[] ser = PrintServiceLookup.lookupPrintServices(null, null);

        System.out.println("**************** All Printers ******************");
        for (int i = 0; i < ser.length; ++i) {
            String p_name = ser[i].getName();
            System.out.println(p_name);
        }
        System.out.println("***********************************************\n");
        defaultPrinter  =   PrintServiceLookup.lookupDefaultPrintService().getName();
        System.out.println("Default Printer  : "+defaultPrinter );
    }

    public static void main(String[] args) {
        new ShowPrinters().SearchPrinter();
    }
}


Read more...

Friday, February 17, 2012

How to Read Property file using Java - Get Database connection parameters from property file

7 comments
  • Here is the java class to read property file which will help to create database connection. 







package jsupport.com.db;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com/
 */
public class ReadPropertyFile {

    public static String db_driver;
    public static String db_url;
    public static String db_username;
    public static String db_password;

    static {
        try {
            Properties prop = new Properties();
            prop.load(new FileInputStream("Config.properties"));

            String driver = prop.getProperty("db_driver");
            String ip = prop.getProperty("db_ip");
            String dbName = prop.getProperty("db_name");

            db_username = prop.getProperty("db_username");
            db_password = prop.getProperty("db_password");

            if (driver.equals("SQL2000")) {
                db_driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
                db_url = "jdbc:microsoft:sqlserver://" + ip + ":1433;DatabaseName=" + dbName;
            } else if (driver.equals("SQL2005")) {
                db_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                db_url = "jdbc:sqlserver://" + ip + ":1433;databaseName=" + dbName;
            } else if (driver.equals("MySQL")) {
                db_driver = "com.mysql.jdbc.Driver";
                db_url = "jdbc:mysql://" + ip + ":3306/" + dbName;
            }

            System.out.println("Database Driver :"+db_driver+ " Database URL :"+db_url);

        } catch (IOException ex) {
            System.out.println("Can not read property file...");
        }
    }
}




  • Create Config.properties under your source code package and add following properties 


Config.properties


# JSupport http://javasrilankansupport.blogspot.com/

#databace properties
#db_driver=SQL2000
#db_driver=SQL2005
db_driver=MySQL
db_ip=localhost
db_name=mysql
db_username=root
db_password=123

Read more...

Wednesday, February 15, 2012

Connect To Access Database Using Java

11 comments
package jsupport.com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Jsupport
 */
public class AccessDatabaseConnection {

    public static Connection connect() {

        Connection con;
        try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Data.mdb;";
            con = DriverManager.getConnection(database, "Admin", "64");

        } catch (Exception ex) {
            return null;
        }
        return con;
    }

    public void getData(){

        try {

            Statement stmt = connect().createStatement();
            ResultSet rset = stmt.executeQuery("SELECT * FROM tblData");

            if (rset.next()) {

                String name     = rset.getString("user_name");
                String email    = rset.getString("user_email");

                System.out.println("Name  : " +name +"  Email : "+email);
            }


        } catch (SQLException ex) {
            
        }
    }

    public static void main(String[] args) {
        new AccessDatabaseConnection().getData();
    }
}



Access Database table


     Data.mdb




Read more...