Java BufferedReader Copy copyFile(String source, String dest)

Here you can find the source of copyFile(String source, String dest)

Description

Copies a file from one location to another

License

Apache License

Parameter

Parameter Description
source a parameter
dest a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void copyFile(String source, String dest) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**//from  w  w w .j  a va2 s  .  c  o  m
     * Copies a file from one location to another
     *
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFile(String source, String dest) throws IOException {
        File s = new File(source);
        File d = new File(dest);
        copyFile(s, d);
    }

    /**
     * Copies from one file to another
     *
     * @param s source file
     * @param d destination file
     * @throws IOException
     */
    public static void copyFile(File s, File d) throws IOException {
        if (!s.canRead())
            throw new IOException("Unable to read source file.");
        if (d.exists() && !d.canWrite())
            throw new IOException("Unable to write dest file");
        if (!d.exists() && !d.createNewFile())
            throw new IOException("Unable to create new file");

        BufferedInputStream is = new BufferedInputStream(new FileInputStream(s));
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(d));
        byte[] b = new byte[1024];
        int amountRead = is.read(b);

        while (amountRead > 0) {
            os.write(b, 0, amountRead);
            amountRead = is.read(b);
        }
        os.close();
        is.close();
    }

    /**
     * Reads data from BufferedReader into a String
     *
     * @param reader
     * @throws IOException
     */
    public static String read(BufferedReader reader) throws IOException {
        StringBuffer tmp = new StringBuffer();
        String tmpS;
        while ((tmpS = reader.readLine()) != null) {
            tmp.append(tmpS);
        }
        return tmp.toString();
    }
}

Related

  1. copyFile(File orgFile, File dstFile)
  2. copyFile(File original, File copy)
  3. copyFile(File source, File dest)
  4. copyFile(File src, File dst)
  5. copyFile(String orig, String dest)
  6. copyFile(String src, String dst)
  7. copyFile(String src, String dst)
  8. copyFile(String srcFile, String dstFile)
  9. copyFile(String srcFileName, String destFileName)