Description
Copy a file from one place to another.
License
Apache License
Parameter
Parameter | Description |
---|
from | source file |
to | destination file |
Exception
Parameter | Description |
---|
IOException | an exception |
Declaration
public static void copyFile(File from, File to) throws IOException
Method Source Code
//package com.java2s;
/*******************************************************************************
* Copyright 2010 Dieselpoint, Inc./*from ww w . ja v a 2 s.c om*/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Main {
/**
* Copy a file from one place to another.
* @param from source file
* @param to destination file
* @throws IOException
*/
public static void copyFile(File from, File to) throws IOException {
RandomAccessFile randFrom = new RandomAccessFile(from, "r");
RandomAccessFile randTo = new RandomAccessFile(to, "rw");
appendFile(randTo, randFrom);
randFrom.close();
randTo.close();
to.setLastModified(from.lastModified());
}
/**
* Copy a file from one place to another.
* @param from source file
* @param to destination file
* @throws IOException
*/
public static void copyFile(String from, String to) throws IOException {
copyFile(new File(from), new File(to));
}
/**
* Append the contents of extra file to main.
*/
public static void appendFile(RandomAccessFile main, RandomAccessFile extra) throws IOException {
// this method uses NIO direct transfer. It delegates the task
// to the operating system. Only works under 1.4+
// Unfortunately, can't use this because it crashes with an out of memory error on big files
//extra.getChannel().transferTo(0, Long.MAX_VALUE, mainFile.getChannel());
byte[] buf = new byte[1024 * 1024]; // 1 mb
main.seek(main.length());
extra.seek(0);
while (true) {
int count = extra.read(buf);
if (count == -1)
break;
main.write(buf, 0, count);
}
}
}
Related
- copyFile(File srcFile, File destFile)
- copyFile(String src, String dst)
- copyFile(String src, String dst)