Combining multiple InputStreams

You can combine two or more inputstreams with the class SequenceInputStream. It allows
you to put them next to each other, in sequence:

           SequenceInputStream
           +-----------------------+
           |  +-----+-----+-----+  |
 read() <--+  | IS1 | IS2 | IS3 |  |
           |  +-----+-----+-----+  |
           +-----------------------+

There are two ways to construct a SequenceInputStream through its two constructors. You could either pass an enumeration of all your inputstreams, or you can pass in two inputstreams.
The following example allows you to specify two filenames which will be printed out on the console.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main {   
   public static void main(String[] args) throws Exception {
      if (args.length != 2) {
         System.out.println("Usage: java Main <filename1> <filename2>");
         System.exit(1);
      }
 
      FileInputStream fis1 = new FileInputStream(args[0]);
      FileInputStream fis2 = new FileInputStream(args[1]);
 
      SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
      int k;
      while ((k = sis.read()) > -1) {
         System.out.print((char) k);
      }
   }
}

(try it out with two small textfiles :)

Converting a character array to a Reader

Use the class CharArrayReader. Once you have wrapped it into a reader, you can use other readers to access the data, as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      char array[] = { 'h', 'e', 'l', 'l', 'o', ',', 'n', 
                       'w', 'o', 'r', 'l', 'd', '!' };
      CharArrayReader car = new CharArrayReader(array);
 
      BufferedReader br = new BufferedReader(car);
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }
}

outputs:

hello,
world!

Listing the contents of a directory in Java

Use the File class. Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File []files = new File(args[0]).listFiles();
 
      for (int i=0; i<files.length; i++) {
         // Checks whether this it's a directory
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

If you want to enable wildcards, you can do all the customization yourself using
FilenameFilter. The following example shows you how to list the .java files in
the directory specified at command line:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File path = new File(args[0]);
      File []files = path.listFiles(
               new FilenameFilter() {
                  public boolean accept(File f, String name) {
                     return name.toLowerCase().endsWith(".java");
                  }
               });
 
      for (int i=0; i<files.length; i++) {
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

Differentiating between left, middle, right mouse click

Here’s some sample code.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) { 
            System.exit(1);
         }
      });
 
      getContentPane().addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
               System.out.print("Left");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
               System.out.print("Middle");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
               System.out.print("Right");
            }
            System.out.println(" mouse button was clicked!");
         }
      });
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Trapping CTRL-C in a Java app

The method addShutdownHook() of the java.lang.Runtime class provides a way of trapping a shutdown of the virtual machine. Please not that this method was added since java version 1.3.

The method expects one argument and that is a Thread object. This thread will be started when the virtual machine terminates. The only way this code will not be executed is when you use the method Runtime.halt().
After you have added a Shutdown hook, it is also possible to remove it with the equivalent method removeShutdownHook(). Its parameter should be the same as the one passed in addShutdownHook.

The following code illustrates an example that makes use of the addShutdownHook method.

Main.java:

// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
  private Thread thread = null;
 
  public Shutdown() {
    thread = new Thread("Sample thread") {
      public void run() {
        while (true) {
          System.out.println("[Sample thread] Sample thread speaking...");
          try {
            Thread.currentThread().sleep(1000);
          } catch (InterruptedException ie) {
            break;
          }
        }
        System.out.println("[Sample thread] Stopped");
      }
    };
    thread.start();
  }

  public void stopThread() {
    thread.interrupt();
  }
}
 
 
// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
  private Shutdown shutdown = null;
 
  public ShutdownThread(Shutdown shutdown) {
    super();
    this.shutdown = shutdown;
  }
  
  public void run() {
    System.out.println("[Shutdown thread] Shutting down");
    shutdown.stopThread();
    System.out.println("[Shutdown thread] Shutdown complete");
  }
}
 
 
// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
  public static void main(String [] args) {
    Shutdown shutdown = new Shutdown();
    try {
      Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
      System.out.println("[Main thread] Shutdown hook added");
    } catch (Throwable t) {
      // we get here when the program is run with java
      // version 1.2.2 or older
      System.out.println("[Main thread] Could not add Shutdown hook");
    }
 
    try {
      Thread.currentThread().sleep(10000);
    } catch (InterruptedException ie) {
    }
    System.exit(0);
  }
}

Converting a boolean to an int

Assuming true maps to 1, false to 0.

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      System.out.println(boolean2Int(true));
      System.out.println(boolean2Int(false));
   } 
 
   public static int boolean2Int(boolean b) {
      return b ? 1 : 0;
   }
}

Determining the component type of an array

Very simple – first obtain the Class object representing the type of the array itself:

  Integer [] arr = new Integer[5];
  Class arrType = arr.getClass();

And then obtain its type using the Class.getComponentType() method:

  Class componentType = arrType.getComponentType();
  System.out.println(componentType.getName());

The above code should print “java.lang.Integer”.

Create an instance of a primitive type using reflection

You have to use the appropriate wrapper classes that are associated with the primitive types:

   boolean    java.lang.Boolean 
   char       java.lang.Character 
   byte       java.lang.Byte 
   short      java.lang.Short 
   int        java.lang.Integer 
   long       java.lang.Long 
   float      java.lang.Float 
   double     java.lang.Double 

This example shows you how to go about creating a Boolean wrapper and converting it to its corresponding primitive type.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         Constructor c = Boolean.class.getConstructor(new Class[] { boolean.class });
         Boolean b = (Boolean) c.newInstance(new Object[] { new Boolean(true) });
 
         boolean result = b.booleanValue();
         System.out.println(result);
      }
      catch(NoSuchMethodException e) {
         System.err.println(e);
      }
      catch(InvocationTargetException e) {
         System.err.println(e);
      }
      catch(InstantiationException e) { 
         System.err.println(e);
      }
      catch(IllegalAccessException e) { 
         System.err.println(e);
      }
   }
}

Using soft references in Java

A soft reference is a type of a reference object that you can use to refere to an object but allow it to become garbage collected only if memory is low and no other normal Java reference is pointing to the object. It can be used for caching purposes where a cached object is only of importance in non-critical situations, but is of no importance when the internal memory is low.

The following example demonstrates this. It creates a soft reference to a StringBuffer, fills up the memory to show that only then this reference object will be garbage-collected:

Main.java:

import java.lang.ref.*;
import java.util.*;
import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      SoftReference sr = new SoftReference(createDummyCacheEntry());
 
      printAccessible(sr);
 
      fillUpMemory();
  
      printAccessible(sr);
   }
 
   public static StringBuffer createDummyCacheEntry() {
      System.out.println("Creating dummy cache entry...");
      StringBuffer sb = new StringBuffer();
 
      for (int i=0; i<100000; i++) {
         sb.append("abcdefghijklmnopqrstuvwxyz");
      }
 
      return sb;
   }      
 
   public static void fillUpMemory() {
      System.out.println("Filling up memory...");
      LinkedList ll = new LinkedList();
      try {
         while (true) {
            ll.add(new Double[999999]);
         }
      } catch(OutOfMemoryError e) {
         ll.clear();
         System.gc();
      }
   }
 
   public static void printAccessible(SoftReference sr) {
      System.out.println("Softreference is" + (sr.get() == null ? " not" : "") + " accessible");
   }
}

outputs:

Creating dummy cache entry...
Softreference is accessible
Filling up memory...
Softreference is not accessible

Convert a String to lowercase or uppercase

The following example is self-explanatory:

public class TestProg
{
    public static void main(String args[])
    {
        String s = "Hello, World!";
        
        String supper = s.toUpperCase();
        String slower = s.toLowerCase();
        
        System.out.println(supper);    // prints out: HELLO, WORLD!
        System.out.println(slower);    // prints out: hello, world!
    }
}

Note: for internationalization purposes, the methods toUpperCase() and toLowerCase() perform some checking for languages as German and Turkish to do the correct conversion.
If you need these functions in time-critical applications, you might want to consider rewriting them without these checkings.