/** * Utility method that moves a file from its current location to the * provided target directory. If rename fails (for example if the target is * another disk) a copy/delete will be performed instead. This is not a rename, * use {@link #renameFile(File, File, CopyOption...)} instead. * * @param toMove The File object to move. * @param targetDirectory the destination directory * @return the new file, null iff the move was unsuccessful * @throws IOException */ public static File moveFileToDirectory( File toMove, File targetDirectory ) throws IOException { if ( !targetDirectory.isDirectory() ) { throw new IllegalArgumentException( "Move target must be a directory, not " + targetDirectory ); } File target = new File( targetDirectory, toMove.getName() ); moveFile( toMove, target ); return target; }
@Test public void moveFile() throws Exception { File file = touchFile( "source" ); File targetDir = directory( "dir" ); File newLocationOfFile = new File( targetDir, "new-name" ); FileUtils.moveFile( file, newLocationOfFile ); assertTrue( newLocationOfFile.exists() ); assertFalse( file.exists() ); assertEquals( newLocationOfFile, targetDir.listFiles()[0] ); }
/** * Utility method that moves a file from its current location to the * provided target directory. If rename fails (for example if the target is * another disk) a copy/delete will be performed instead. This is not a rename, * use {@link #renameFile(File, File, CopyOption...)} instead. * * @param toMove The File object to move. * @param targetDirectory the destination directory * @return the new file, null iff the move was unsuccessful * @throws IOException */ public static File moveFileToDirectory( File toMove, File targetDirectory ) throws IOException { if ( !targetDirectory.isDirectory() ) { throw new IllegalArgumentException( "Move target must be a directory, not " + targetDirectory ); } File target = new File( targetDirectory, toMove.getName() ); moveFile( toMove, target ); return target; }