Saturday, April 28, 2012

How to exploit Java.NIO for copying files in Java


Java NIO provide a powerful solution for copying files:

    public void Copy_File(String from, String where) throws IOException {

        FileChannel inChannel = new FileInputStream(from).getChannel();
        FileChannel outChannel = new FileOutputStream(where).getChannel();

        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }

No comments:

Post a Comment