Monday, August 23, 2010

Java Robot Class in Java

This is a quick snap of using Robot class of Java. You can find full article on keyboard and mouse events here.
package test;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Main{
    public static void main(String args[]) throws AWTException
    {
        Robot robot = new Robot();

       int keyEvent[] = {
            KeyEvent.VK_H,
            KeyEvent.VK_E,
            KeyEvent.VK_L,
            KeyEvent.VK_L,
            KeyEvent.VK_O,
            
        };
       for(int i = 0; i < keyEvent.length; i++)
       {
          robot.keyPress(keyEvent[i]);
          robot.delay(1000);
       }

    }
}

Tuesday, August 17, 2010

Yahoo mail is down without noticing users.

Yahoo mail is down without noticing users about any scheduled maintenance. When I try to access yahoo mail, I get different kinds of error massages including LaunchFFC-1. These are the screenshots.







And is this an attack? or are they updating yahoo mail?

Friday, August 13, 2010

How to make a Socket Connection?

This program creates a socket connection to the server of atomic clock in Boulder, Colorado.

import java.io.*;
import java.net.*;
import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        try
        {
            Socket time = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            try
            {
                InputStream inStream = time.getInputStream();
                Scanner in = new Scanner(inStream);

                while(in.hasNext())
                {
                    String line = in.nextLine();
                    System.out.println(line);
                }
            }
            finally
            {
                time.close();
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Thursday, August 12, 2010

Java - Files and Streams Summary Part 2

1.6 File Streams


The classes FileInputStream and FileOutputStream define byte input and output streams that are connected to files.

FileInputStream(File file) - Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

FileInputStream(String name) - Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

FileInputStream(FileDescriptor fdObj) - Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.


FileOutputStream(File file) - Creates a file output stream to write to the file represented by the specified File object.


FileOutputStream(File file, boolean append) - Creates a file output stream to write to the file represented by the specified File object.


FileOutputStream(FileDescriptor fdObj) - Creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.


FileOutputStream(String name) - Creates an output file stream to write to the file with the specified name.


FileOutputStream(String name, boolean append) - Creates an output file stream to write to the file with the specified name.








Java - Files and Streams Summary Part 1

1.1  Introduction.
Java.io package provides an extensive library of classes to deal with input and output. Java provides streams as a general mechanism for dealing with data  I/O.

There are three kinds of streams.

  1. Byte Streams 
  2. Character Streams
  3. Buffered Streams
An input stream - an object that an application use to read sequence of data, acts as a source of data.
An output stream - an object that an application use to write a sequence of data, acts as a destination of data.

Entities work as output or input streams.

  1. An array of character or bytes.
  2. A file
  3. A pipe 
  4. A network connection
1.2 File Class

File(String pathname)
          Creates a new File instance by converting the given pathname string into an abstract pathname.

Methods

  1. String getName() - Returns the name of the file, excluding directory file resides.
  2. String getPath() - Returns the (absolute or relative) pathname of the file.
  3. String getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
  4. Stirng getCononicalPath() - Platform-dependent. Returns the canonical form of this abstract pathname.
  5. String getParent() -  The parent part of the pathname of this File object is returned if one exists, otherwise the null value is returned.
  6. boolean isAbsolute() - Whether a File object represents an absolute pathname can be determined using this method.
  7. long lastModified() - Returns the time that the file denoted by this abstract pathname was last modified.
  8. long length() - Returns the size (in bytes) of the file represented by the File object.
  9. boolean equals(Object obj) - This method only compares the pathnames of the File objects, and returns true if they are identical.
  10. boolean exists() - Return true if specified file or directory is existed.
  11. boolean isFile() - Return true if the object is a file.
  12. boolean isDirectory() - Returns true if the object is a directory.
  13. boolean canRead() - Returns true if the object has read access.
  14. boolean canWrite() - Returns true if the object has writing access.
  15. String[] list() - Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
  16. String[] list(FileNameFilter filter) -  Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
1.3 Creating New Files and Directories
  1. boolean  createNewFile() throws IOException  - Creates  a new, empty file named by the abstract pathname if,and only if, a file with this name does not already exist. Return value is true if the file is created, else false means file is already exists.
  2. boolean mkdir() - Creates the directory named by this abstract pathname.
  3. boolean mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
1.4 Rename Files and Directories
  1. boolean renameTo(File dest) - Renames the file denoted by this abstract pathname.
1.5 Deleting Files and Directories
  1.  boolean delete() -  Deletes the file or directory denoted by this abstract pathname.

Wednesday, August 11, 2010

How create a zip file by Java

To write ZIP file, we use ZipOutputStream  class. For each file we want to put into the zip file, we create ZipEntry object and pass the file name to the ZipEntry constructor, it automatically sets other parameters such as file properties and decompression method. If you need to override these settings read Java API. Then we call the putNextEntry method of the ZipOutputStream to begin writing new file. Send the file data to the zip stream. After we close the Entry by calling closeEntry().

Here is the demonstration. I tested it and work like a charm.

//import classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.*;

//Declaration of class Main
public class Main
{
  // Main method
  public static void main(String[] args)
  {
     //File path objects
     String source1 = "E:\\Pictures\\Elly\\elly1.jpg";
     String source2 = "E:\\Pictures\\Elly\\elly3.jpg";
     String source3 = "E:\\Pictures\\Elly\\elly5.jpg";

     //To create array
     String sources[] = {source1, source2, source3};

     //Create a buffer for reading files
     byte[] buf = new byte[1024];



     try
     {
         //To create target zip file
         String target = "E:\\target.zip";
         ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));

         for(int i=0;i 0)
             {
                 zos.write(buf, 0, len);
             }
             //complete Entry
             zos.closeEntry();
             zos.close();
         }
         //complete stream
         zos.close();

     }
     // catch Exceptions
     catch(IOException e)
     {
         System.out.println(e);
     }

  }
}

P.S
JAR files are simply ZIP files with another entry, the so-called manifest. You use the JarInputStream and JarOutputStream classes to read and write the manifest entry.

How to read a zip file in Java?

This is not a basic tutorial but I just learned it, so I gonna show you how to write simple command line program to read content of zip file.

ZIP archives store one or more files in compressed format. Each ZIP archive has a header with information such as the name of the file and the compression method that was used.

In Java, ZipInputStream class use to read zip archives. To read zip file content one must check each individual entry in the zip file. The getNextEntry() method returns an object of type ZipEntry that describes zip entry. The read method of the ZipInputStream is modified to return -1 at the end of the current entry (instead of just at the end of the ZIP file). You must call closeEntry() method to read the next entry.

Here is my demonstration code I written.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.ZipInputStream;


public class Main
{
  public static void main(String[] args) throws Exception
  {
      String file = "D:\\kiss.zip";
      try
      {
          FileInputStream fis = new FileInputStream(file);
          ZipInputStream zis = new ZipInputStream(fis);
          ZipEntry ze = null;
          while((ze = zis.getNextEntry()) != null)
          {
              System.out.println(ze.getName());
              zis.closeEntry();
          }
          zis.close();
      }
      catch(FileNotFoundException e)
      {
          System.out.println(e);
      }
      catch(IOException e)
      {
          System.out.println(e);
      }
        
  }
}

The ZIP input stream throws a ZipException when there is an error in reading a ZIP file. Normally this error occurs when the ZIP file has been corrupted.

Visual guide to set up classpath in java.

Click "Start" => "My Computer"


Click on the main drive


Go to "Program Files" (Mostly "C:\Program Files") Now Find Java Folder

Open JDK Folder - Where the Compiler is

In the JDK folder right click on any file item and choose "Properties".

From the "Properties Window" click "Location" and Copy the folder path.(In my computer: "C:\Program Files\Java\jdk1.6.0_16\bin")

Now go to Desktop (or Start => My Computer) and Right click on the My Computer and click "Properties".
In "System Properties" click on the "Advanced" tab.
Now Click on the "Environment Variables".
In the Environment Variable window click "New" to create a new variable
Now in the Variable Name field type "Path" without " mark.
And Variable value is where the compiler is(we copied it...remember..)... Paste it here(Mine is C:\Program Files\Java\jdk1.6.0_16\bin)
Now click ok.

To test:
Go to command line(Start Menu => Run => type "cmd" without " marks.


Now type "javac" without " marks.
If you see something like this.... Usage: javac .....
You correctly did it....

Installing and Getting Started In Java

This is a guide to download, install and setup environment to develop applications with Java Standard Edition.

Step 1
Download Java Development Kit Link
Choose Java SE edition and download installation file, once you download and install JDK you may have to set up the class path.

Step 2
Follow following steps to set up class path in Windows XP.
Click "Start" => "My Computer"(Computer in Vista)
Click "C:\" drive (click the drive your "Programs Files" are installed.
Go to "Program Files" (Mostly "C:\Program Files")
Go to Folder called "Java"
In the "Java" folder click the folder "JDK" (In my computer folder path is "C:\Program Files\Java\jdk1.6.0_16" - Where the compiler is...)
In the JDK folder right click on any file item and choose "Properties".
From the "Properties Window" click "Location" and Copy the folder path.(In my computer: "C:\Program Files\Java\jdk1.6.0_16\bin")

Now go to Desktop and Right click on the My Computer and click "Properties".
In "System Properties" click on the "Advanced" tab.
Now Click on the "Environment Variables".
In the Environment Variable window click "New" to create a new variable.
Now in the Variable Name field type "Path" without " mark.
And Variable value is where the compiler is(we copied it...remember..)... Paste it here(Mine is C:\Program Files\Java\jdk1.6.0_16\bin)
Now click ok.

To test:
Go to command line(Start Menu => Run => type "cmd" without " marks.
Now type "javac" without " marks.
If you see something like this.... Usage: javac .....
You correctly did it....

Let me tell about me...

I am Isuru from Sri Lanka. I am a student of Information Technology(IT). This blog is writing while I am learning how to program in Java. This is not just a blog that posts source codes. I hope to post things I learn from my life experience. Because programming means finding solutions for real life problems. I use object-oriented programming paradigm, because most advanced and popular languages use object-oriented paradigm because it is often relate to particular real world concepts.

I use Java and Python to demonstrate how to start learn and build advanced programs.

Please consider that I am a student and I am not a experienced programmer in the industry, so there may be errors and easy methods to some functions to replace. So your kind feedback is really appreciated.