Java FileInputStream Copy copyFile(String sourcePath, String newPath)

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

Description

Copy an existing file to a new location.

License

Open Source License

Parameter

Parameter Description
sourcePath The original file to be copied
newPath The new location for the copy to go

Return

Returns true if the copy was successful, returns false if an error occurred.

Declaration

public static boolean copyFile(String sourcePath, String newPath) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013 MCForge./*from   w w  w.  ja  v  a2  s.  c  om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 ******************************************************************************/

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 {
    /**
     * Copy an existing file to a new location.
     * 
     * @param sourcePath The original file to be copied
     * @param newPath The new location for the copy to go
     * 
     * @return Returns true if the copy was successful, returns false if an error occurred.
     */
    public static boolean copyFile(String sourcePath, String newPath) {
        InputStream inStream = null;
        OutputStream outStream = null;

        try {

            File afile = new File(sourcePath);
            File bfile = new File(newPath);

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

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

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

            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

Related

  1. copyFile(String sourceFile, String targetFolder)
  2. copyFile(String sourceFile, String targetFolder)
  3. CopyFile(String sourceFilePath, String destinationFilePath)
  4. copyFile(String sourceFilePath, String destinationFilePath)
  5. copyFile(String sourceFilePath, String destinationFilePath)
  6. copyFile(String src, File dest)
  7. copyFile(String src, String dest)
  8. copyFile(String src, String dest)
  9. copyFile(String src, String dest)