28 Feb 2014

File copying in different locations


package Anusoftwares.FileCopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class Testing {
static ArrayList<String> dest=null;
static String source=null;
public static void main(String[] args) {
source="D:/Data/Baby pics/271.jpg";
dest=new ArrayList<String>();
//added the destination paths.
dest.add("D:/Data/data1");
dest.add("D:/Data/dat2");
dest.add("D:/Data/data3");
fileCopie(source,dest);
}
//file copier method
private static void fileCopie(String source2, ArrayList<String> dest2) {
InputStream is = null;
ArrayList<OutputStream> destArr=new ArrayList<OutputStream>();
File file=new File(source);
    String fname=file.getName();
    System.out.println(fname);
for(int i=0;i<dest2.size();i++){
try {
File dest1=new File(dest2.get(i));
dest1.mkdirs();
dest1=new File(dest1,fname);
OutputStream os = new FileOutputStream(dest1);
destArr.add(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
   try {
   
       is = new FileInputStream(source);
       for(String dest:dest2){
       
       }
       byte[] buffer = new byte[1024];
       int length;
       while ((length = is.read(buffer)) > 0) {
           for(OutputStream os:destArr){
           os.write(buffer, 0, length);
           }
       }
   }catch(Exception e){
    e.printStackTrace();
   } finally {
       try {
        if(is!=null){
is.close();
        }
        for(OutputStream os:destArr){
           if(os!=null){
            os.flush();
            os.close();
           }
           }
} catch (IOException e) {
e.printStackTrace();
}
       
   }
}

}

No comments:

Post a Comment