Here you can find the source of copyFile(File source, File target)
Parameter | Description |
---|---|
source | the source file |
target | the target file |
public static boolean copyFile(File source, File target)
//package com.java2s; /*//from w ww. j ava2s . c o m * Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * * File utility functions * */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Main { /** * File copy buffer size */ private static final int COPY_BUFFER_SIZE = 4096; /** * Creates a copy of a file * * @param source * the source file * @param target * the target file * @return true if written successfully */ public static boolean copyFile(File source, File target) { boolean backup = true; try { byte[] buf = new byte[COPY_BUFFER_SIZE]; FileInputStream fis = new FileInputStream(source); OutputStream fos = createOutputStream(target); int len; do { len = fis.read(buf); if (len > 0) { fos.write(buf, 0, len); } } while (len > 0); fis.close(); fos.close(); } catch (Exception e) { backup = false; } return backup; } /** * Creates a file output stream. This creates directories and overwriting * possible read-only flag * * @param file * the file * @return the file output stream * @throws FileNotFoundException * if file cannot be created */ public static OutputStream createOutputStream(File file) throws FileNotFoundException { File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileOutputStream fos; try { fos = new FileOutputStream(file); } catch (IOException e) { if (file.exists()) { file.delete(); } fos = new FileOutputStream(file); } return new BufferedOutputStream(fos); } }