Java FileInputStream Copy copyFile(String oldPath, String newPath)

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

Description

Copy file at oldPath to newPath.

License

Open Source License

Parameter

Parameter Description
oldPath Old path to file. This file at this path will be copied.
newPath New path to file. This will be the location of the new copied file.

Exception

Parameter Description
IOException Occurs if any exceptions are thrown while reading thefile or writing to the file.

Declaration

public static void copyFile(String oldPath, String newPath) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

public class Main {
    /**/*from w  w  w.ja  v  a  2s .  co m*/
     * Copy file at oldPath to newPath.
     * 
     * If a file already exists at newPath, file at oldPath will NOT be copied.
     * 
     * @param oldPath Old path to file. This file at this path will be copied.
     * @param newPath New path to file. This will be the location of the new
     *            copied file.
     * @throws IOException Occurs if any exceptions are thrown while reading the
     *             file or writing to the file.
     */
    public static void copyFile(String oldPath, String newPath) throws IOException {
        InputStream inStream = null;
        OutputStream outStream = null;
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        if (newFile.exists()) {
            return;
        }

        System.out.println(String.format("Copying file at %s to %s", oldPath, newPath));

        inStream = new FileInputStream(oldFile);
        outStream = new FileOutputStream(newFile);

        byte[] buffer = new byte[1024];

        int length;
        while ((length = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, length);
        }

        inStream.close();
        outStream.close();
    }
}

Related

  1. copyFile(String inFile, String outFile)
  2. copyFile(String inFileName, String outFileName)
  3. copyFile(String input, String output)
  4. copyFile(String inputFile, String outputFile)
  5. copyFile(String oldFile, String newFile)
  6. copyFile(String oldPath, String newPath)
  7. copyFile(String oldPathFile, String newPathFile)
  8. copyFile(String original, String copy)
  9. copyFile(String pathOld, String pathNew)