Java examples for File Path IO:File Move
Moves a file.
/*//from w ww . j a v a2 s . c om * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.Closeable; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; public class Main{ public static void main(String[] argv) throws Exception{ File srcFile = new File("Main.java"); File destFile = new File("Main.java"); moveFile(srcFile,destFile); } /** * The file copy buffer size (30 MB) */ private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30; /** * Moves a file. * <p> * When the destination file is on another file system, do a "copy and delete". * * @param srcFile the file to be moved * @param destFile the destination file * @throws NullPointerException if source or destination is <code>null</code> * @throws FileExistsException if the destination file exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file * @since Commons IO 1.4 */ public static void moveFile(File srcFile, File destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } if (!srcFile.exists()) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (destFile.exists()) { throw new IOException("Destination '" + destFile + "' already exists"); } if (destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' is a directory"); } boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile, destFile); if (!srcFile.delete()) { CommonsFileUtils.deleteQuietly(destFile); throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } } /** * Copies a file to a new location preserving the file date. * <p> * This method copies the contents of the specified source file to the * specified destination file. The directory holding the destination file is * created if it does not exist. If the destination file exists, then this * method will overwrite it. * <p> * <strong>Note:</strong> This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be <code>null</code> * @param destFile the new file, must not be <code>null</code> * * @throws NullPointerException if source or destination is <code>null</code> * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File) */ public static void copyFile(File srcFile, File destFile) throws IOException { copyFile(srcFile, destFile, true); } /** * Copies a file to a new location. * <p> * This method copies the contents of the specified source file * to the specified destination file. * The directory holding the destination file is created if it does not exist. * If the destination file exists, then this method will overwrite it. * <p> * <strong>Note:</strong> Setting <code>preserveFileDate</code> to * <code>true</code> tries to preserve the file's last modified * date/times using {@link File#setLastModified(long)}, however it is * not guaranteed that the operation will succeed. * If the modification operation fails, no indication is provided. * * @param srcFile an existing file to copy, must not be <code>null</code> * @param destFile the new file, must not be <code>null</code> * @param preserveFileDate true if the file date of the copy * should be the same as the original * * @throws NullPointerException if source or destination is <code>null</code> * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs during copying * @see #copyFileToDirectory(File, File, boolean) */ private static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } if (srcFile.exists() == false) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (srcFile.isDirectory()) { throw new IOException("Source '" + srcFile + "' exists but is a directory"); } if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); } File parentFile = destFile.getParentFile(); if (parentFile != null) { if (!parentFile.mkdirs() && !parentFile.isDirectory()) { throw new IOException("Destination '" + parentFile + "' directory cannot be created"); } } if (destFile.exists() && destFile.canWrite() == false) { throw new IOException("Destination '" + destFile + "' exists but is read-only"); } doCopyFile(srcFile, destFile, preserveFileDate); } /** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, can be <code>null</code> * @return <code>true</code> if the file or directory was deleted, otherwise * <code>false</code> * * @since Commons IO 1.4 */ public static boolean deleteQuietly(File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (Exception ignored) { } try { return file.delete(); } catch (Exception ignored) { return false; } } /** * Internal copy file method. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { closeQuietly(output); closeQuietly(fos); closeQuietly(input); closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } /** * Cleans a directory without deleting it. * * @param directory directory to clean * @throws IOException in case cleaning is unsuccessful */ private static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } IOException exception = null; for (File file : files) { try { forceDelete(file); } catch (IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } } /** * Unconditionally close an <code>InputStream</code>. * <p> * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p> * Example code: * <pre> * byte[] data = new byte[1024]; * InputStream in = null; * try { * in = new FileInputStream("foo.txt"); * in.read(data); * in.close(); //close errors are handled * } catch (Exception e) { * // error handling * } finally { * IOUtils.closeQuietly(in); * } * </pre> * * @param input the InputStream to close, may be null or already closed */ public static void closeQuietly(InputStream input) { closeQuietly((Closeable) input); } /** * Unconditionally close an <code>OutputStream</code>. * <p> * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p> * Example code: * <pre> * byte[] data = "Hello, World".getBytes(); * * OutputStream out = null; * try { * out = new FileOutputStream("foo.txt"); * out.write(data); * out.close(); //close errors are handled * } catch (IOException e) { * // error handling * } finally { * IOUtils.closeQuietly(out); * } * </pre> * * @param output the OutputStream to close, may be null or already closed */ public static void closeQuietly(OutputStream output) { closeQuietly((Closeable) output); } /** * Unconditionally close a <code>Closeable</code>. * <p> * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p> * Example code: * <pre> * Closeable closeable = null; * try { * closeable = new FileReader("foo.txt"); * // process closeable * closeable.close(); * } catch (Exception e) { * // error handling * } finally { * IOUtils.closeQuietly(closeable); * } * </pre> * * @param closeable the object to close, may be null or already closed * @since Commons IO 2.0 */ private static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } /** * Deletes a file. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>You get exceptions when a file or directory cannot be deleted. * (java.io.File methods returns a boolean)</li> * </ul> * * @param file file or directory to delete, must not be <code>null</code> * @throws NullPointerException if the directory is <code>null</code> * @throws FileNotFoundException if the file was not found * @throws IOException in case deletion is unsuccessful */ public static void forceDelete(File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent) { throw new FileNotFoundException("File does not exist: " + file); } String message = "Unable to delete file: " + file; throw new IOException(message); } } } }