Wednesday, 10 August 2011

Copying one file to another

import java.io.*;

public class CopyFile{
  private static void copyfile(String srFile, String dtFile){
  try{
  File f1 = new File(srFile);
  File f2 = new File(dtFile);
  InputStream in = new FileInputStream(f1);
  
  //For Append the file.
//  OutputStream out = new FileOutputStream(f2,true);

  //For Overwrite the file.
  OutputStream out = new FileOutputStream(f2);

  byte[] buf = new byte[1024];
  int len;
  while ((len = in.read(buf)) > 0){
  out.write(buf, 0, len);
  }
  in.close();
  out.close();
  System.out.println("File copied.");
  }
  catch(FileNotFoundException ex){
  System.out.println(ex.getMessage() + " in the specified directory.");
  System.exit(0);
  }
  catch(IOException e){
  System.out.println(e.getMessage()); 
  }
  }
  public static void main(String[] args){
  switch(args.length){
  case 0: System.out.println("File has not mentioned.");
    System.exit(0);
  case 1: System.out.println("Destination file has not mentioned.");
  System.exit(0);
  case 2: copyfile(args[0],args[1]);
  System.exit(0);
  default : System.out.println("Multiple files are not allow.");
  System.exit(0);
  }
  }
}

Wednesday, 27 July 2011

Example of Date class

Q. How to current date?
     We can use Date class to use current date
Sample Code:
import java.util.*;

public class  DateDemo{
  public static void main(String[] args) {
  Date d=new Date();
  System.out.println("Today date is "+ d);
  }

Redirect to System.out

Q. How to redirect System.out?
A: Use System.setOut()
Sample code:
import java.io.*;
class Redirection {
  public static void main(String args[]) throws IOException {
    PrintStream pos =
new PrintStream(new FileOutputStream("applic.log"));
    PrintStream oldstream=System.out;
    System.out.println("Message 1 appears on console");
    System.setOut(pos);                 
    System.out.println("Message 2 appears on file"); 
    System.out.println("Message 3 appears on file");
    System.out.println("Message 4 appears on file");
    System.setOut(oldstream);
    System.out.println("Message 5 appears on console");
    System.out.println("Message 6 appears on console");        
  }
}