Wednesday, October 29, 2014

Making Executable Jar File


Creating an executable JAR file. Here is the general procedure for creating an executable JAR:

1. Compile your java code (for ex: Hello.java), generating all of the program's class files.

2. Create a manifest file containing the following 2 lines: (named as Hello.mf)
Manifest-Version: 1.0
Main-Class: Hello  (name of the main class)

Note: The name of the file should end with the .mf suffix. It is important that the file ends with a blank line.

3. To create the JAR, open command prompt and type the following command:
jar cmf manifest-file jar-file input-files
Ex: jar cmf Hello.mf Hello.jar *.java *.class

Note: The input-files must include any class files, images, sounds, etc. that your program uses. Optionally, you can include the program's .java files in the JAR. See below for adding directories to  the JAR.

4. To view the contents of the JAR, type:
jar tf jar-file
Ex: jar tf Hello.jar

5. Execute the application from the command line by typing:
java -jar jar-file

Ex: java -jar Hello.jar

Monday, October 13, 2014

Try-with-resources in Java 7

Try-with-resources in Java 7

Try-with-resources in Java 7 is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block.

Resource Management With Try-Catch-Finally, Old School Style 

Managing resources that need to be explicitly closed is somewhat tedious before Java 7.
private static void printFile() throws IOException {
    InputStream input = null;

    try {
        input = new FileInputStream("file.txt");

        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    } finally {
        if(input != null){
            input.close();
        }
    }
}
The code marked in bold is where the code can throw an Exception. As you can see, that can happen in 3 places inside the try-block, and 1 place inside the finally-block.

The finally block is always executed no matter if an exception is thrown from the try block or not. That means, that the InputStream is closed no matter what happens in the try block. Or, attempted closed that is. TheInputStream's close() method may throw an exception too, if closing it fails.

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...