Monday, August 31, 2015

Copy and paste a file by java



import java.io.*;
import javax.swing.*;

public class Copy {

    
    public void copyFile() {
        
       /* Delcare the main */
        FileInputStream from = null;
        FileOutputStream to = null;
        String savefile = "";
        File file = null;
        File file2 = null;
        
        /* Select  file to copy */
        JFileChooser fileChooser = new JFileChooser();
        /* you can set a filter to copy specific file type. Example: jpg & png image files*/
        //FileNameExtensionFilter filter = new FileNameExtensionFilter("Image (*.jpg  *.png)", "jpg", "png"); 
        //fileChooser.setFileFilter(filter);
        int showOpenDialog = fileChooser.showOpenDialog(null);
        
        if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
        }
        if (file != null) {
            /* select location and give a file name */
            JFileChooser fileChooser2 = new JFileChooser();
            fileChooser2.showSaveDialog(null);
            file2 = fileChooser2.getSelectedFile();
            savefile = file2.getAbsolutePath() + file.getName();
        }
        
        try {
            if (file != null & file2 != null) {
                from = new FileInputStream(file);
                to = new FileOutputStream(savefile);
                /* Seperate file to byte array for copying */
                byte[] buffer = new byte[4096];
                int byteRead;
                /* writng new file */
                while( (byteRead = from.read(buffer)) != -1) {
                    to.write(buffer, 0, byteRead);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            /* always close FileInputStream & FileOutputStream */
            try {
                if(from != null) {
                    from.close();
                }
                if(to != null) {
                    to.close();
                    System.out.println("Copied to - " + savefile);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * main method
     */
    public static void main(String[] args) {
        Copy copy = new Copy();
        copy.copyFile();
    }
}

0 comments:

Post a Comment