Renaming and deleting a file in Java

Rename:

Use the method renameTo in the File class. If the destination folder is different from the source folder, it will move the file to the destination folder. Eg.

import java.io.*;
 
public class FileRename 
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.renameTo(new File("c:\test2.txt"));
 
      System.out.println(file.getName());
   }

}

Notice that, after renaming, getName returns the old filename. Bug? Anyone?

Delete:

Use the method delete in the File class. Eg.

import java.io.*;
 
public class FileDelete
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.delete();
   }
}

Changing the mouse cursor when moving over a component

Add a mouse listeners to the component and set another cursor when the mouse
enters it. Set it to the default cursor when the mouse moves out of it.

Here’s an example that creates a JFrame with a number of buttons, each with
a different mouse cursor. Our method createCursor will associate a cursor
to a component.

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   private Vector buttons = new Vector();
     
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
      buttons.addElement(CreateCursor(new JButton("DEFAULT_CURSOR"), Cursor.DEFAULT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("CROSSHAIR_CURSOR"), Cursor.CROSSHAIR_CURSOR));
      buttons.addElement(CreateCursor(new JButton("TEXT_CURSOR"), Cursor.TEXT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("WAIT_CURSOR"), Cursor.WAIT_CURSOR));
      buttons.addElement(CreateCursor(new JButton("SW_RESIZE_CURSOR"), Cursor.SW_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("SE_RESIZE_CURSOR"), Cursor.SE_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("NW_RESIZE_CURSOR"), Cursor.NW_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("NE_RESIZE_CURSOR"), Cursor.NE_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("N_RESIZE_CURSOR"), Cursor.N_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("S_RESIZE_CURSOR"), Cursor.S_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("W_RESIZE_CURSOR"), Cursor.W_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("E_RESIZE_CURSOR"), Cursor.E_RESIZE_CURSOR));
      buttons.addElement(CreateCursor(new JButton("HAND_CURSOR"), Cursor.HAND_CURSOR));
      buttons.addElement(CreateCursor(new JButton("MOVE_CURSOR"), Cursor.MOVE_CURSOR));
 
	getContentPane().setLayout(new GridLayout(buttons.size(), 1));
 
      for (int i=0; i<buttons.size(); i++) {
         getContentPane().add((JButton) buttons.elementAt(i));
      }
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   private JComponent CreateCursor(final JComponent component, final int cursor) {
	component.addMouseListener(new MouseAdapter() {
	   public void mouseEntered(MouseEvent e) {
		component.setCursor(Cursor.getPredefinedCursor(cursor));
	   }
	   public void mouseExited(MouseEvent e) {
		component.setCursor(Cursor.getDefaultCursor());
	   }
 	});
 
      return component;
   }  
}

Determining the OS at runtime

Use the following code to get information about the operating system:

   System.out.println("OS Name: " + System.getProperty("os.name"));
   System.out.println("OS Architecture: " + System.getProperty("os.arch"));
   System.out.println("OS Version: " + System.getProperty("os.version"));

Output will be something like:

   OS Name: Windows NT
   OS Architecture: x86
   OS Version: 4.0

Converting a hexadecimal value to a byte

The Byte class has a static method decode that can decode decimal, hexadecimal and octal values.

Main.java:

public class Main {
   public static void main(String args[]) throws Exception {
      byte b = Byte.decode("0x0a").byteValue();
  
      System.out.println(b);
   }
}

outputs

10

Performing a fast array copy

The System class contains a method called arraycopy that copies an array or part of an array to another one. You specify a source array (the elements that are being copied) and a destination array (where the elements should go). You should have allocated enough memory for the destination array to hold the new values. Also, you can specify the source offset that indicates from what index the copying should start and an destination offset that indicates what index the values should be copied to. The types of the source array and destination array should match (eg. you can’t copy elements from an object array into an integer array) or an ArrayStoreException will be thrown.

This example copies 5 elements from arr starting from index 3 into arr2 starting from index 0.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9 };
      int arr2[] = new int[5];
      System.arraycopy(arr, 3, arr2, 0, 5);
 
      System.out.print("arr:nt");
      printArray(arr);
      System.out.print("arr2:nt");
      printArray(arr2);
   }      
 
   public static void printArray(int []arr) {
      for (int i=0; i<arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }
}

Instantiating an array using reflection

Use the java.lang.reflect.Array class.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      // instantiation of an array of primitives
      int primitives[] = (int[]) Array.newInstance(int.class, 10);
 
      System.out.println(primitives);
 
      // instantiation of an array of objects
      Main objects[] = (Main[]) Array.newInstance(Main.class, 10);
 
      System.out.println(objects);
   }
}

Executing a Linux shell script from Java

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String args[]) {
      try {
         Process p = Runtime.getRuntime().exec("run.sh"); 
         
         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);
      }
   }
}

Excellent book:
Unix Shells by Example

Converting a primitive to a String

There are several ways you can do this. In Java programs, you will often see that a primitive is converted by using the concatenation operator on Strings (“” + primitive).
A more performant way is to use the method toString on the Object that represents the primitive or to use the static function valueOf in the String class.
Here’s an example:

public class TestProg
{
    public static void main(String args[])
    {
        short   p_short = 4;
        int     p_int = 10;
        long    p_long = 2349945821828L;
        float   p_float = 3.1415F;
        double  p_double = 0.00000000004D;
        boolean p_boolean = false;
        char    p_char = 'E';
        char    p_array[] = { 'e', 's', 'u', 's' };


        System.out.println(""+p_short);                 // 4
        System.out.println(Short.toString(p_short));    // 4
        System.out.println(String.valueOf(p_short));    // 4   (casted to an int!)
        
        System.out.println(""+p_int);                   // 10
        System.out.println(Integer.toString(p_int));    // 10
        System.out.println(String.valueOf(p_int));      // 10
        
        System.out.println(""+p_long);                  // 2349945821828
        System.out.println(Long.toString(p_long));      // 2349945821828
        System.out.println(String.valueOf(p_long));     // 2349945821828
        
        System.out.println(""+p_float);                 // 3.1415
        System.out.println(Float.toString(p_float));    // 3.1415
        System.out.println(String.valueOf(p_float));    // 3.1415
        
        System.out.println(""+p_double);                // 4.0E-11
        System.out.println(Double.toString(p_double));  // 4.0E-11
        System.out.println(String.valueOf(p_double));   // 4.0E-11
        
        System.out.println(""+p_boolean);               // false
        System.out.println(new Boolean(p_boolean).toString());  // false
        System.out.println(String.valueOf(p_boolean));  // false
        
        System.out.println(""+p_char);                  // E
        System.out.println(new Character(p_char).toString());   // E
        System.out.println(String.valueOf(p_char));     // E
        
        System.out.println(""+p_array);                 // esus
        System.out.println(p_array.toString());         // [C@1a
        System.out.println(String.valueOf(p_array));    // esus
    }
}

(Notice that the Boolean and Character classes do not have a static method toString(). In that case, you have to instantiate an object and call the toString method on it.)

To test out the difference in performance of using toString() or valueOf() over ""+p, I ran the following test:

public class TestPerformance
{
    public static void main(String args[])
    {
        double  p_double = 0.00000000004D;
        long start, end;

        System.out.println("Converting to String using concatenation");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = "" + p_double;
        end = System.currentTimeMillis();        
        System.out.println("tElapsed time: " + (end - start));
        

        System.out.println("Converting to String using valueOf");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = String.valueOf(p_double);
        end = System.currentTimeMillis();
        System.out.println("tElapsed time: " + (end - start));


        System.out.println("Converting to String using toString");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = Double.toString(p_double);
        end = System.currentTimeMillis();
        System.out.println("tElapsed time: " + (end - start));      
    }
}

The output (times may vary!) shows a performance gain of almost 20%!

Converting to String using concatenation
	Elapsed time: 5270
Converting to String using valueOf
	Elapsed time: 4230
Converting to String using toString
	Elapsed time: 4230

Passing the output of one thread as the input to another (using readers/writers)

A pipe is a communication channel between two threads. It is typically used in producer-consumer systems where one thread produces data (producer) necessary for the other thread (consumer) to operate. In Java, a pipe is implemented by connecting a PipedReader instance to a PipedWriter instance:

   PipedWriter producer = new PipedWriter();
   PipedReader consumer = new PipedReader(producer);

All data written to producer will be stored in a pipe (buffer) until the consumer reads it.

In this example, a thread mimics the behavior of scores for 10 contestants coming in by generating random numbers between [0, 10[. Another thread keeps track of the total votes per contestant.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main {   
   public static void main(String[] args) throws Exception {
      PipedWriter producer = new PipedWriter();
      PipedReader consumer = new PipedReader(producer);
 
      NumberProducer np = new NumberProducer(producer);
      NumberConsumer nc = new NumberConsumer(consumer);
 
      np.start();
      nc.start();
   }
}
 
class NumberProducer extends Thread
{
   BufferedWriter bw;
 
   public NumberProducer(Writer w) {
      this.bw = new BufferedWriter(w);
   }
 
   // thread continually produces random votes
   public void run() {
      try {
         Random r = new Random();
         while (true) {
            String vote = "" + Math.abs((r.nextInt() % 10));
 
            bw.write(vote);
            bw.newLine();
            bw.flush();
 
            sleep(10);
         }  
      }   
      catch(IOException e) {
         System.err.println(e);
      }
      catch(InterruptedException e) {
         System.err.println(e);
      }      
   }
}
 
class NumberConsumer extends Thread
{
   BufferedReader br;
   int[] votes = new int[10];
  
   public NumberConsumer(Reader r) {
      br = new BufferedReader(r);
   }
 
   public void run() {
      try {
         String line;
         int count = 0;
         while ((line = br.readLine()) != null) {
            int contestant = Integer.parseInt(line);
            votes[contestant]++;
 
            count++;
            if (count % 100 == 0) 
               printVotes();
         }      
      }   
      catch(IOException e) {
         System.err.println(e);
      }
   }
 
   public void printVotes() {
      for (int i=0; i<votes.length; i++) {
         System.out.println("Contestant #" + i + ": " + votes[i]);
      }
      System.out.println("——————");
   }
}

outputs:

Contestant #0: 7
Contestant #1: 8
Contestant #2: 10
Contestant #3: 15
Contestant #4: 5
Contestant #5: 11
Contestant #6: 4
Contestant #7: 15
Contestant #8: 16
Contestant #9: 9
------------------
Contestant #0: 22
Contestant #1: 22
Contestant #2: 26
Contestant #3: 21
Contestant #4: 11
Contestant #5: 18
Contestant #6: 13
Contestant #7: 26
Contestant #8: 26
Contestant #9: 15
------------------
Contestant #0: 32
Contestant #1: 29
Contestant #2: 37
Contestant #3: 30
Contestant #4: 29
Contestant #5: 31
Contestant #6: 22
Contestant #7: 35
Contestant #8: 34
Contestant #9: 21
------------------
. . .

Getting the value for e or for pi

Both E (the base of the natural logarithms) and PI
(the ratio of the circumference of a circle to its diameter)
are defined in the Math class as static member variables of type double.
e = 2.7182818284590452354
pi = 3.14159265358979323846

System.out.println(Math.E);    // 2.718281828459045
System.out.println(Math.PI);   // 3.141592653589793