Reading a BufferedImage using the ImageIO API

The new ImageIO API allows you to read and write any type of image files as long
as there is a plug-in written for it. Those plug-ins can be provided by third parties.
The appropriate plug-in is choosen depending on the file suffix, mime type, contents or format name.

The following example uses the built-in JPG plug-in.

Main.java:

import javax.swing.event.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   BufferedImage background;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      try {
         background = ImageIO.read(new URL("http://www.esus.com/images/mong.jpg"));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public void paint(Graphics g) {
      g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Who is calling a method

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      test();
   }
 
   public static void test() {
      System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      new Main().new Inner().innerTest();
   }
 
   class Inner {
      public void innerTest() {
         System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      }
   }
}

FlowInspector.java:

public class FlowInspector
{
   public static String getCallingMethod() {
      try {
         StringWriter sw = new StringWriter();
         (new Exception()).printStackTrace(new PrintWriter(sw));
         StringReader sr = new StringReader(sw.getBuffer().toString());
         BufferedReader br = new BufferedReader(sr);
         br.readLine();
         br.readLine();
         br.readLine(); 
         String line = br.readLine();
         line = line.trim().substring(3);
         line = line.substring(0, line.indexOf('('));
 
         return line;
      } catch (Exception e) {
         e.printStackTrace();
      }
 
      return null;
   }
}

Running Main yields:

Method that called me: Main.main
Method that called me: Main.test

Creating multi-dimensional arrays

Examine the following double array:

      double ar[][] = 
        { { 20.0 },
          { 20.0, 19 },
          { 20.0, 19.0, 18.0 },
          { 20.0, 19.0, 18.0, 17.0 },
          { 20.0, 19.0, 18.0, 17.0, 16.0 } };

You can achieve the same setup dynamically by looping through the row indices and dynamically creating a array with variable length:

public class Main {
   public static void main(String []args) {
      double ar[][] = null;
 
      ar = new double[5][];
      for (int i=0; i<ar.length; i++) {
         ar[i] = new double[i+1];
         for (int j=0; j<i+1; j++) {
            ar[i][j] = (double) 20 - j;
         }
      }
 
      for (int i=0; i<ar.length; i++) {
         for (int j=0; j<ar[i].length; j++) {
            System.out.print(ar[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Filling in new trace information in the stack trace of an Exception

The stack trace is useful to determine where the exception was thrown. There may be times where you need to rethrow an exception and find out where it was rethrown. You can use the method fillInStackTrace for that.

Main.java:

public class Main {
   public static void main(String args[]) {
      try {
         methodWithException1();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void methodWithException1() throws Exception {
      try {
         methodWithException2();
      }
      catch(Exception e) {
         throw (Exception) e.fillInStackTrace();
//         throw e;
      }
   }
 
   public static void methodWithException2() throws Exception {
      throw new Exception("some extra info");
   }
}

outputs:

java.lang.Exception: some extra info
        at Main.methodWithException1(Main.java:16)
        at Main.main(Main.java:4)

If you would have written throw e instead of throw (Exception e.fillInStackTrace, the output would have been:

java.lang.Exception: some extra info
        at Main.methodWithException2(Main.java:22)
        at Main.methodWithException1(Main.java:13)
        at Main.main(Main.java:4)

Accessing array elements through reflection

You can do so with Array.get.

Main.java:

import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      int[]   intArray    = new int[] { 1, 2, 3, 4, 5 };
      int[][] intintArray = new int[][] { { 1, 2}, {3, 4}, {5} };
      
      printArray(intArray);
      System.out.println();
      printArray(intintArray);
   }
 
   public static void printArray(Object array) {
      int arrayLength = Array.getLength(array);
      Class componentClass = array.getClass().getComponentType(); 
 
      System.out.println("Array length     " + arrayLength);
      System.out.println("Component class  " + componentClass);
      System.out.println("Array contents");
      for (int i=0; i<arrayLength; i++) {
         Object element = Array.get(array, i);
         if (element.getClass().isArray()) {
            printArray(element);
         }
         else {
            System.out.print(Array.get(array, i) + " ");
         }
      }
      System.out.println();
   }
}

outputs:

Array length     5
Component class  int
Array contents
1 2 3 4 5

Array length     3
Component class  class [I
Array contents
Array length     2
Component class  int
Array contents
1 2
Array length     2
Component class  int
Array contents
3 4
Array length     1
Component class  int
Array contents
5

Executing an batch file from Java

Start the process using the Runtime class. Using the methods getInputStream and getOutputStream, you can manipulate the input- and outputstreams of the batch file.
Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String args[]) {
      try {
         Process p = Runtime.getRuntime().exec("run.bat"); 
         
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
 
         bw.write("1");
         bw.flush();
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
         br.close();
         bw.close();
 
         System.out.println(p.exitValue());
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

run.bat:

@echo off
choice /c123 /n
if errorlevel 1 echo first
if errorlevel 2 goto second
if errorlevel 3 goto third
exit

first:
echo First option
exit

second:
echo Second option
exit

third:
echo Third option
exit

Problem: returning an exitcode from a batch file to the calling Java app doesn’t seem to work. anyone?

Converting a String to an InputStream

Main.java:

import java.io.*;

public class Main
{
   public static void main(String []args) throws Exception {
      String s = "hello world!";
      
      InputStream is = getInputStream(s, "UTF-8");
      int c;
      while ((c = is.read()) > -1) {
         System.out.print((char) c);
      }
      System.out.println();
   }
   
   public static InputStream getInputStream(String s, String encoding) throws UnsupportedEncodingException {
      return new ByteArrayInputStream(s.getBytes(encoding));
   }
}

The Unicode general category types

Each Unicode character belongs to a certain category. According to the API, “the character attribute tables for specific version of Unicode are available in various subdirectories of ftp://ftp.unicode.org/Public/

0  -  UNASSIGNED			
1  -  UPPERCASE_LETTER			'A', ...
2  -  LOWERCASE_LETTER			'a', ...
3  -  TITLECASE_LETTER		
4  -  MODIFIER_LETTER
5  -  OTHER_LETTER
6  -  NON_SPACING_MARK
7  -  ENCLOSING_MARK
8  -  COMBINING_SPACING_MARK
9  -  DECIMAL_DIGIT_NUMBER
10 -  LETTER_NUMBER
11 -  OTHER_NUMBER
12 -  SPACE_SEPARATOR
13 -  LINE_SEPARATOR
14 -  PARAGRAPH_SEPARATOR
15 -  CONTROL
16 -  FORMAT
18 -  PRIVATE_USE
19 -  SURROGATE
20 -  DASH_PUNCTUATION
21 -  START_PUNCTUATION
22 -  END_PUNCTUATION
23 -  CONNECTOR_PUNCTUATION
24 -  OTHER_PUNCTUATION
25 -  MATH_SYMBOL
26 -  CURRENCY_SYMBOL
27 -  MODIFIER_SYMBOL
28 -  OTHER_SYMBOL

Seeding the random number generator

You can set the seed of the Random class manually:

   Random r = new Random(10);
   
   or
  
   Random r = new Random();
   r.setSeed(10);

ie:

import java.util.*;
 
public class Main 
{  
   public static void main(String args[]) {
      Random r = new Random(10);
      for (int i=0; i<10; i++) {
         float f = r.nextFloat();
         System.out.println(f);
      }
   }
}

outputs:

0.73043025
0.44563425
0.25780278
0.41291267
0.059201956
0.67215943
0.2441172
0.36817038
0.818809
0.3567646

Running the app another time will yield the same pseudo-random numbers.

Downloading a remote file in Java

Create an instance of the URL class, open the TCP stream and read the data
from the inputstream provided by the URL object.
Following code demonstrates this:

import java.net.*;
import java.io.*;
  
public class Main
{
   public static void main(String args[]) 
   {
      try {
         if (args.length != 1) {
            System.err.println("Usage: java Main <URL>");
            System.exit(0);
         }
 
         URL url = new URL(args[0]);
         InputStream in = url.openStream();
 
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
  
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (MalformedURLException e) {
         System.err.println (e);
      }
      catch (IOException e) {
         System.err.println (e);
      }
   }
}

prints the following to standard output:

<html>
<body>
<h1> HELLO WORLD! </h1>
</body>
</html>