Java FileInputStream Copy copyFile(String fileName, String fromDir, String toDir)

Here you can find the source of copyFile(String fileName, String fromDir, String toDir)

Description

Utility method to copy a file from one directory to another

License

Open Source License

Declaration

public static void copyFile(String fileName, String fromDir, String toDir) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    /**//from  w  ww.j a v  a2  s  .co  m
     * Utility method to copy a file from one directory to another
     */
    public static void copyFile(String fileName, String fromDir, String toDir) throws IOException {

        copyFile(new File(fromDir + File.separator + fileName), new File(toDir + File.separator + fileName));

    }

    /**
     * Utility method to copy a file from one directory to another
     */
    public static void copyFile(File from, File to) throws IOException {

        if (!from.canRead()) {
            throw new IOException("Cannot read file '" + from + "'.");
        }

        if (to.exists() && (!to.canWrite())) {
            throw new IOException("Cannot write to file '" + to + "'.");
        }

        FileInputStream fis = new FileInputStream(from);
        FileOutputStream fos = new FileOutputStream(to);

        byte[] buf = new byte[1024];

        int bytesLeft;
        while ((bytesLeft = fis.available()) > 0) {
            if (bytesLeft >= buf.length) {
                fis.read(buf);
                fos.write(buf);
            } else {
                byte[] smallBuf = new byte[bytesLeft];
                fis.read(smallBuf);
                fos.write(smallBuf);
            }
        }

        fos.close();
        fis.close();
    }
}

Related

  1. copyFile(InputStream in, String destFile)
  2. copyFile(OutputStream out, InputStream in)
  3. copyFile(String f1, String f2)
  4. copyFile(String fileIn, String fileOut)
  5. copyFile(String fileInName, String fileOutName)
  6. copyFile(String fileOutPut, String fileIn)
  7. copyFile(String from, String to)
  8. copyFile(String fromFile, String toFile)
  9. copyFile(String fromFilePath, String toFilePath)