Saturday, April 28, 2012

How to exploit buffers for copying files in Java


A classic approach of copying files in Java is based on buffers transfer. The below tip put this approch into a simple and compact method.

    public void CopyFile(String from, String where) {

        BufferedInputStream buff = null;
        BufferedOutputStream buffout = null;

        try {
            buff = new BufferedInputStream(new FileInputStream(from));
            buffout = new BufferedOutputStream(new FileOutputStream(where));

            int b = 0;
            byte[] bytes = new byte[1024];

            while (b != -1) {
                b = buff.read(bytes);
                buffout.write(bytes);
            }
            System.out.println("File written !");
        } catch (Exception e) {
            System.out.println("File not written !");
        } finally {
            try {
                buff.close();
                buffout.flush();
                buffout.close();
            } catch (Exception e) {
            }
        }
    }

No comments:

Post a Comment