Sunday, May 11, 2014

Simple java program to copy files on any OS.


  • This is a simple java program to copy files from anywhere to anywhere in the file system and on any operating system.
  • Scanner in util package to make inputs dynamic.
  • Using the program you just have to enter source of input file with file name and destination where it has to be placed.
  • The code calculates the time taken for the processing too.

 package com.objectStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.util.Scanner;  
 public class DemoObjectStreamRead {  
      static long startTime = System.currentTimeMillis();  
      static Scanner scanner = new Scanner(System.in);  
      static final String FORWARD_SLASH = "/";  
      static final String COLON = ":";  
      public static void main(String[] args) throws IOException {  
           System.out.println("Enter source: ");  
           String inputFile = scanner.next();  
           String file = "";  
           file = inputFile.split(COLON)[1];  
           System.out.println("Enter destination folder(s)");  
           String outputFile = scanner.next();  
           if (!new File(outputFile).exists()) {  
                new File(outputFile).mkdirs();  
           }  
           outputFile = outputFile.concat(FORWARD_SLASH + file);  
           File ipFile = new File(inputFile);  
           File opFile = new File(outputFile);  
           InputStream is = new FileInputStream(ipFile);  
           int read = 0;  
           byte[] bytes = new byte[1024];  
           FileOutputStream os = new FileOutputStream(opFile);  
           while ((read = is.read(bytes)) != -1) {  
                os.write(bytes, 0, read);  
           }  
           is.close();  
           os.flush();  
           os.close();  
           long endTime = System.currentTimeMillis();  
           long time = endTime - startTime;  
           System.out.println("time taken: " + (double) time / 100 / 60 + " mins");  
      }  
 }  

Feel free to comment. Suggestions and comments are appreciated.

Comments

blog comments powered by Disqus