Here you can find the source of rename(File srcFile, String newName)
Parameter | Description |
---|---|
srcFile | an existing file to rename, must not be <code>null</code> |
newName | the new filename, must not be <code>null</code> |
Parameter | Description |
---|---|
NullPointerException | if srcFile or newName is <code>null</code> |
IOException | if the newFile has exist |
public static void rename(File srcFile, String newName) throws IOException
//package com.java2s; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Main { /**/*from w ww. j av a2s . co m*/ * rename. * * @param srcFile an existing file to rename, must not be <code>null</code> * * @param newName the new filename, must not be <code>null</code> * * @throws NullPointerException if srcFile or newName is <code>null</code> * * @throws IOException if source is not exist or is directory * * @throws IOException if the newFile has exist */ public static void rename(File srcFile, String newName) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (newName == null || newName.length() == 0) { throw new NullPointerException("newName 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"); } String parentPath = srcFile.getParentFile().getAbsolutePath(); File newFile = new File(parentPath + File.separator + newName); if (newFile.exists()) { throw new IOException("Rename '" + srcFile + "' exists ,can not rename"); } if (!srcFile.renameTo(newFile)) { throw new IOException("Can not rename from '" + srcFile + "' to '" + newFile + "'"); } } }