Here you can find the source of copyFile(String source, String destination)
Parameter | Description |
---|---|
source | source file |
destination | destination file |
public static void copyFile(String source, String destination) throws IOException
//package com.java2s; /*//from w ww .j a va 2 s . c o m * DAITSS Copyright (C) 2007 University of Florida * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class Main { /** * Method to copy a single file. Works for relative and absolute paths. * * @param source * source file * @param destination * destination file * @exception IOException * if operation fails */ public static void copyFile(String source, String destination) throws IOException { File src = new File(source); File dest = new File(destination); // Make sure the specified source exists, is readable, and is a file. if (!src.isFile()) throw new IOException("SubAccount " + src + "is not a file"); if (!src.canRead()) throw new IOException("SubAccount " + src + "is unreadable"); // get directory of destination File newDir = new File(destination.substring(0, destination.lastIndexOf(File.separator))); // if the destination directory doesn't already exist, then try to // create it (and all // intermediate directories) if (!newDir.exists()) { if (!newDir.mkdirs()) { throw new IOException("Unable to create directories: " + dest); } } // create input and output streams for byte transfer FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); // transfer bytes in 8K chunks byte[] buffer = new byte[8 * 1024]; while (true) { int bytes_read = fis.read(buffer); if (bytes_read == -1) break; fos.write(buffer, 0, bytes_read); } // close input/output streams if (fis != null) try { fis.close(); fis = null; } catch (IOException e) { ; } if (fos != null) try { fos.close(); fos = null; } catch (IOException e) { ; } // clean up src = null; dest = null; newDir = null; } }