List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:jp.primecloud.auto.process.puppet.PuppetNodeProcess.java
protected void backupManifest(Long instanceNo) { Instance instance = instanceDao.read(instanceNo); File manifestFile = new File(manifestDir, instance.getFqdn() + ".base.pp"); if (!manifestFile.exists()) { return;//w ww. j a v a 2 s . c o m } // ?? File backupDir = new File(manifestDir, "backup"); File backupFile = new File(backupDir, manifestFile.getName()); try { if (!backupDir.exists()) { backupDir.mkdir(); } if (backupFile.exists()) { FileUtils.forceDelete(backupFile); } FileUtils.moveFile(manifestFile, backupFile); } catch (IOException e) { // ?? log.warn(e.getMessage()); } }
From source file:jeplus.RadianceWinTools.java
/** * Call a sequence of DaySim programs to run the simulation * @param config Radiance Configuration/* w ww . j av a2s. co m*/ * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runDaySim(RadianceConfig config, String WorkDir, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; // Manipulate header file HashMap<String, String> props = new HashMap<>(); // props.put("project_name", ""); props.put("project_directory", "./"); props.put("bin_directory", config.getResolvedDaySimBinDir()); props.put("tmp_directory", "./"); props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/DefaultTemplate.htm"); props.put("sensor_file", in); try { FileUtils.moveFile(new File(WorkDir + File.separator + model), new File(WorkDir + File.separator + model + ".ori")); } catch (IOException ex) { logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex); } DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model, props); // Run gen_dc command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("gen_dc"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing gen_dc", ex); } // Run ds_illum command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_illum"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_illum", ex); } // Run ds_el_lighting command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_el_lighting"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_el_lighting", ex); } // Return Radiance exit value return ExitValue; }
From source file:ch.entwine.weblounge.dispatcher.impl.handler.PreviewRequestHandlerImpl.java
/** * Creates the preview image for the given resource and returns an input * stream to the preview or <code>null</code> if the preview could not be * created./*from w w w .j av a 2 s . c om*/ */ private InputStream createPreview(WebloungeRequest request, WebloungeResponse response, Resource<?> resource, Language language, ImageStyle style, PreviewGenerator previewGenerator, File previewFile, ContentRepository contentRepository) { String pathToImageFile = previewFile.getAbsolutePath(); boolean firstOne = true; // Make sure the preview is not already being generated by another thread synchronized (previews) { while (previews.contains(pathToImageFile)) { logger.debug("Preview at {} is being created, waiting for it to be generated", pathToImageFile); firstOne = false; try { previews.wait(500); if (previews.contains(pathToImageFile)) { logger.trace("After waiting 500ms, preview at {} is still being worked on", pathToImageFile); DispatchUtils.sendServiceUnavailable(request, response); return null; } } catch (InterruptedException e) { DispatchUtils.sendServiceUnavailable(request, response); return null; } } // Make sure others are waiting until we are done if (firstOne) { previews.add(pathToImageFile); } } // Determine the resource's modification date long resourceLastModified = ResourceUtils.getModificationDate(resource, language).getTime(); // Create the preview if this is the first request if (firstOne) { ResourceURI resourceURI = resource.getURI(); if (style != null) logger.info("Creating preview of {} with style '{}' at {}", new String[] { resource.getIdentifier(), style.getIdentifier(), pathToImageFile }); else logger.info("Creating original preview of {} at {}", new String[] { resource.getIdentifier(), pathToImageFile }); // Get hold of the content ResourceContent resourceContents = resource.getContent(language); // Get the mime type final String mimetype = resourceContents.getMimetype(); final String format = mimetype.substring(mimetype.indexOf("/") + 1); boolean scalingFailed = false; InputStream is = null; FileOutputStream fos = null; try { is = contentRepository.getContent(resourceURI, language); // Remove the original image FileUtils.deleteQuietly(previewFile); // Create a work file File imageDirectory = previewFile.getParentFile(); String workFileName = "." + UUID.randomUUID() + "-" + previewFile.getName(); FileUtils.forceMkdir(imageDirectory); File workImageFile = new File(imageDirectory, workFileName); // Create the scaled image fos = new FileOutputStream(workImageFile); logger.debug("Creating scaled image '{}' at {}", resource, previewFile); previewGenerator.createPreview(resource, environment, language, style, format, is, fos); // Move the work image in place try { FileUtils.moveFile(workImageFile, previewFile); } catch (IOException e) { logger.warn("Concurrent creation of preview {} resolved by copy instead of rename", previewFile.getAbsolutePath()); FileUtils.copyFile(workImageFile, previewFile); FileUtils.deleteQuietly(workImageFile); } finally { previewFile.setLastModified(Math.max(new Date().getTime(), resourceLastModified)); } // Make sure preview generation was successful if (!previewFile.isFile()) { logger.warn("The file at {} is not a regular file", pathToImageFile); scalingFailed = true; } else if (previewFile.length() == 0) { logger.warn("The scaled file at {} has zero length", pathToImageFile); scalingFailed = true; } } catch (ContentRepositoryException e) { logger.error("Unable to load image {}: {}", new Object[] { resourceURI, e.getMessage(), e }); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", resourceURI, e.getMessage()); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", resourceURI, t.getMessage()); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); try { if (scalingFailed && previewFile != null) { logger.info("Cleaning up after failed scaling of {}", pathToImageFile); File f = previewFile; FileUtils.deleteQuietly(previewFile); f = previewFile.getParentFile(); while (f != null && f.isDirectory() && (f.listFiles() == null || f.listFiles().length == 0)) { FileUtils.deleteQuietly(f); f = f.getParentFile(); } } } catch (Throwable t) { logger.warn("Error cleaning up after failed scaling of {}", pathToImageFile); } synchronized (previews) { previews.remove(pathToImageFile); previews.notifyAll(); } } } // Make sure whoever was in charge of creating the preview, was // successful boolean scaledImageExists = previewFile.isFile(); boolean scaledImageIsOutdated = previewFile.lastModified() < resourceLastModified; if (!scaledImageExists || scaledImageIsOutdated) { logger.debug("Apparently, preview rendering for {} failed", previewFile.getAbsolutePath()); DispatchUtils.sendServiceUnavailable(request, response); return null; } else { try { return new FileInputStream(previewFile); } catch (Throwable t) { logger.error("Error reading content from preview at {}: {}", previewFile.getAbsolutePath(), t.getMessage()); DispatchUtils.sendServiceUnavailable(request, response); return null; } } }
From source file:com.edgenius.wiki.service.impl.BackupServiceImpl.java
@Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void restore(File file) throws BackupException, InvalidLicenseException { log.info("Restore starting...."); long time = System.currentTimeMillis(); FileInputStream zipis = null; try {/*from www . j a v a 2 s .com*/ //unzip to temporary directory first String dir = FileUtil.createTempDirectory(TMP_RESTORE); zipis = new FileInputStream(file); ZipFileUtil.expandZipToFolder(zipis, dir); log.info("Restore file unzipped to {}. Took {}s", dir, (System.currentTimeMillis() - time) / 1000); //get databinder, to check options File binderFile = new File(FileUtil.getFullPath(dir, OBJS_BINDER_NAME)); //version check - it may has different fields name etc to cause need do migrate int binderVersion = versionCheck(binderFile); log.info("Data binder version is {}", binderVersion); time = System.currentTimeMillis(); FileInputStream bis = new FileInputStream(binderFile); InputStreamReader reader = new InputStreamReader(bis, Constants.UTF8); XStream xstream = createXStreamInstance(); DataBinder binder = (DataBinder) xstream.fromXML(reader); reader.close(); bis.close(); log.info("Parse binder XML took {}s", (System.currentTimeMillis() - time) / 1000); int leftUserCount = licenseCheck(binder); //As HL Robert's export, Page has list has duplicated: such as page id=93 is enclosed DataObject normally, //but, unexpected, same page appear again in page list, this time it is as a referenece object, but this cause same page //has duplicate ojbect in return list //<com.edgenius.wiki.model.Page reference="93"/> //Here is just temporary fix only for HL. But the fix is Hibernate.loadAll() see BaseDAOHibernate.getAll() List<Page> pages = (List<Page>) binder.get(Page.class.getName()); Set<Integer> dup = new HashSet<Integer>(); for (Iterator<Page> iter = pages.iterator(); iter.hasNext();) { Integer uid = iter.next().getUid(); if (dup.contains(uid)) { log.error("There are duplciated pages while import data, UID:" + uid); iter.remove(); continue; } dup.add(uid); } Map<Integer, String> spaceMap = null; if (binderVersion <= 2180) { //a bug fix - for older 2.18 version as customized theme use spaceUid as key, which changed after import... //Since 2.19, customized theme XML is removed, this problem doesn't exist any more. I found this bug when 2.19:( List<Space> spaces = (List<Space>) binder.get(Space.class.getName()); //save old version spaceUname and spaceUid into a map spaceMap = new HashMap<Integer, String>(); for (Iterator<Space> iter = spaces.iterator(); iter.hasNext();) { Space space = iter.next(); spaceMap.put(space.getUid(), space.getUnixName()); } } int options = binder.getOptions(); if ((options & BACKUP_DATA) > 0) { time = System.currentTimeMillis(); importData(binder, dir, binderVersion); log.info("Restore database table took {}s", (System.currentTimeMillis() - time) / 1000); //delete binder file after import success if (!binderFile.delete()) binderFile.deleteOnExit(); } time = System.currentTimeMillis(); if ((options & BACKUP_ATTACHMENT) > 0) { FileUtils.deleteDirectory(repositoryLocation.getFile()); FileUtils.moveDirectory(new File(FileUtil.getFullPath(dir, binder.getDir(BACKUP_ATTACHMENT))), repositoryLocation.getFile()); } if ((options & BACKUP_RSS) > 0) { FileUtils.deleteDirectory(rssLocation.getFile()); FileUtils.moveDirectory(new File(FileUtil.getFullPath(dir, binder.getDir(BACKUP_RSS))), rssLocation.getFile()); } if ((options & BACKUP_INDEX) > 0) { FileUtils.deleteDirectory(indexLocation.getFile()); FileUtils.moveDirectory(new File(FileUtil.getFullPath(dir, binder.getDir(BACKUP_INDEX))), indexLocation.getFile()); } if ((options & BACKUP_SKIN) > 0) { FileUtils.deleteDirectory(skinLocation.getFile()); FileUtils.moveDirectory(new File(FileUtil.getFullPath(dir, binder.getDir(BACKUP_SKIN))), skinLocation.getFile()); } if ((options & BACKUP_THEME) > 0) { FileUtils.deleteDirectory(themeLocation.getFile()); FileUtils.moveDirectory(new File(FileUtil.getFullPath(dir, binder.getDir(BACKUP_THEME))), themeLocation.getFile()); if (binderVersion <= 2180) { //rename customized theme to new spaceUid File customizedDir = new File(themeLocation.getFile(), "customized"); File customizedSubDir = new File(themeLocation.getFile(), "customizedTemp"); String[] files = customizedDir.list(FileFilterUtils.suffixFileFilter(".xml")); if (files.length > 0) { customizedSubDir.mkdirs(); } for (String name : files) { int uid = NumberUtils.toInt(name.substring(0, name.length() - 4), -1); if (uid == -1) { log.info("Unable to get correct space UID from theme file name {}", name); continue; } String uname = spaceMap.get(uid); if (uname == null) { log.warn("Unable to get old spaceUname by UID {}", uid); continue; } Space space = spaceDAO.getByUname(uname); if (space == null) { log.warn("Unable to get space by Uname {}", uname); continue; } uid = space.getUid(); FileUtils.moveFile(new File(customizedDir, name), new File(customizedSubDir, uid + ".xml")); } if (customizedSubDir.exists()) { //replace old by renamed themes FileUtils.deleteDirectory(customizedDir); FileUtils.moveDirectory(customizedSubDir, customizedDir); } } } //upgrade data file under DataRoot -- Here assume theme, index, rss etc. All use default name from DataRoot!!! try { upgradeService.doBackupPackageUpgardeForDataFiles(String.valueOf((float) binderVersion / 1000)); } catch (Exception e) { log.error("Unexpected erorr while upgrade backup export package from " + binderVersion + " to " + Version.VERSION, e); } log.info("Restore data root files tooks {}s", (System.currentTimeMillis() - time) / 1000); try { FileUtil.deleteDir(dir); } catch (IOException e) { log.error("Unable to delete restore temp directory " + dir); } Version.LEFT_USERS = leftUserCount; log.info("Restore success complete. Database transaction will submit."); } catch (InvalidLicenseException e) { log.error("Restore failed", e); throw e; } catch (Exception e) { log.error("Restore failed", e); throw new BackupException(e); } finally { if (zipis != null) { try { zipis.close(); } catch (Exception e) { } } } }
From source file:jp.primecloud.auto.process.lb.PuppetLoadBalancerProcess.java
protected void restoreManifest(File manifestFile) { // ?/* ww w . ja v a2s .co m*/ File backupDir = new File(manifestDir, "backup"); File backupFile = new File(backupDir, manifestFile.getName()); if (!backupFile.exists()) { return; } try { if (manifestFile.exists()) { FileUtils.forceDelete(manifestFile); } FileUtils.moveFile(backupFile, manifestFile); } catch (IOException e) { // ? log.warn(e.getMessage()); } }
From source file:com.taobao.android.tools.APatchTool.java
@Override public PatchFile doPatch() throws Exception { APatchFile patchFile = new APatchFile(); ApatchInput apatchInput = (ApatchInput) input; mappingMap = apatchInput.mappingMap; if (apatchInput.mappingMap.get(apatchInput.replaceAnnotation) != null) { MethodReplaceAnnotation.ANNOTATION = apatchInput.mappingMap.get(apatchInput.replaceAnnotation); }//from w w w .ja v a 2 s . c om File patchTmpDir = new File(input.outPutFile.getParentFile(), "apatch-tmp"); patchTmpDir.mkdirs(); patchFile.aDiffText = new File(input.outPutFile.getParentFile(), "apatch-diff.txt"); patchFile.diffJson = new File(input.outPutFile.getParentFile(), "apatch-diff.json"); FileUtils.deleteQuietly(patchFile.aDiffText); patchFile.aDiffText.createNewFile(); // unzip apk File unzipFolder = unzipApk(patchTmpDir); final File newApkUnzipFolder = new File(unzipFolder, NEW_APK_UNZIP_NAME); final File baseApkUnzipFolder = new File(unzipFolder, BASE_APK_UNZIP_NAME); // first generate main bundle patch file List<File> aPatches = createBundleAPatch(newApkUnzipFolder, baseApkUnzipFolder, patchTmpDir, apatchInput.andfixMainBundleName, patchFile.aDiffText, patchFile.diffJson); // second generate common bundle patch file // Collection<File> soFiles = FileUtils.listFiles(newApkUnzipFolder, new String[] { "so" }, true); if (input.splitDiffBundle != null) { for (Pair<BundleBO, BundleBO> bundle : input.splitDiffBundle) { if (bundle.getFirst() == null || bundle.getSecond() == null) { continue; } List<File> aPatchFiles = processBundleFiles(bundle.getSecond().getBundleFile(), bundle.getFirst().getBundleFile(), patchTmpDir, patchFile.aDiffText, patchFile.diffJson); if (null != aPatchFiles) { for (File aPatchFile : aPatchFiles) { if (null != aPatchFile && aPatchFile.exists()) { aPatches.add(aPatchFile); } } } } } for (File soFile : soFiles) { String relativePath = PathUtils.toRelative(newApkUnzipFolder, soFile.getAbsolutePath()); if (null != apatchInput.notIncludeFiles && pathMatcher.match(apatchInput.notIncludeFiles, relativePath)) { continue; } File baseSoFile = new File(baseApkUnzipFolder, relativePath); if (PatchUtils.isBundleFile(soFile)) { // if bundle file List<File> aPatchFiles = processBundleFiles(soFile, baseSoFile, patchTmpDir, patchFile.aDiffText, patchFile.diffJson); if (null != aPatchFiles) { for (File aPatchFile : aPatchFiles) { if (null != aPatchFile && aPatchFile.exists()) { aPatches.add(aPatchFile); } } } } } if (aPatches.size() <= 0) { throw new Exception("No apatch files! No classes modify!"); } // merge apatch file File[] aPatchFiles = new File[aPatches.size()]; aPatchFiles = aPatches.toArray(aPatchFiles); File mergePatchFile = null; if (null != aPatchFiles && aPatchFiles.length > 1) { MergePatch mergePatch = new MergePatch(aPatchFiles, apatchInput.projectArtifactId, patchTmpDir); mergePatchFile = mergePatch.doMerge(); } else if (null != aPatchFiles && aPatchFiles.length == 1) { mergePatchFile = aPatchFiles[0]; } if (null != mergePatchFile && mergePatchFile.exists()) { FileUtils.moveFile(mergePatchFile, input.outPutFile); } FileUtils.deleteDirectory(unzipFolder); FileUtils.deleteDirectory(patchTmpDir); patchFile.patchFile = input.outPutFile; return patchFile; }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
/** * Check to see if the file exists. If it doesn't then move it to the new location. * //from www. ja v a 2 s. c o m * @param from File - The file in the old location. * @param to File - The file in the new location. * @throws IOException during move. */ public static void checkAndMoveFile(File from, File to) throws IOException { // If the directory doesn't exist create it. File parentDir = to.getParentFile(); if (!parentDir.exists()) { EPADFileUtils.makeDirs(parentDir); } if (!to.exists()) { // log.info("Moving file to: "+to.getCanonicalPath()); FileUtils.moveFile(from, to); } else { // log.info("Not moving file since it already exists. file="+to.getCanonicalPath()); FileUtils.deleteQuietly(from); } }
From source file:ml.shifu.shifu.core.processor.TrainModelProcessor.java
protected int runTensorflowDistributedTrain() throws Exception { LOG.info("Started {} tensorflow distributed training.", isDryTrain ? "dry " : ""); globalDefaultConfFile = new Path(super.pathFinder .getAbsolutePath(new Path("conf" + File.separator + "global-default.xml").toString())); LOG.info("Shifu tensorflow on yarn global default file is found in: {}.", globalDefaultConfFile); // if not continuous mode, remove tmp models to not load it in tf python, continuous mode here there is a bug cleanTmpModelPath();/* w ww.ja v a 2 s . c o m*/ final List<String> args = new ArrayList<String>(); args.add("-libjars"); addTensorflowRuntimeJars(args); // copy globalconfig example from common conf path to project folder for user to update and modify generateGlobalConf(); args.add("-globalconfig"); // include python env path, args.add(globalDefaultConfFile.getName()); try { String clazz = "ml.shifu.shifu.core.yarn.client.TensorflowClient"; Method main = Class.forName(clazz).getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() }); try { main.invoke(null, (Object) args.toArray(new String[0])); } catch (Exception e) { LOG.error("executing tensorflow client fails", e); return -1; } Path modelPath = HDFSUtils.getFS() .makeQualified(new Path(super.getPathFinder().getModelsPath(SourceType.HDFS))); if (ShifuFileUtils.getFileSystemBySourceType(SourceType.HDFS).exists(modelPath)) { Path localModelsPath = new Path(super.getPathFinder().getModelsPath(SourceType.LOCAL)); if (HDFSUtils.getLocalFS().exists(localModelsPath)) { HDFSUtils.getLocalFS().delete(localModelsPath, true); } copyModelToLocal(null, modelPath, SourceType.HDFS); } else { LOG.warn("Model {} isn't there, maybe job is failed, for bagging it can be ignored.", modelPath.toString()); } } finally { try { FileUtils.moveFile(new File(globalDefaultConfFile.getName().toString()), new File(globalDefaultConfFile.getName() + "_" + System.currentTimeMillis())); } catch (Exception e) { LOG.warn("Failed to move tf-yarn conf file, such message can be ignored!"); } } return 0; }
From source file:jp.primecloud.auto.process.puppet.PuppetNodesProcess.java
protected void restoreManifest(Long instanceNo) { Instance instance = instanceDao.read(instanceNo); File manifestFile = new File(manifestDir, instance.getFqdn() + ".base_coordinate.pp"); // ?/*from ww w. j a va2 s . c o m*/ File backupDir = new File(manifestDir, "backup"); File backupFile = new File(backupDir, manifestFile.getName()); if (!backupFile.exists()) { return; } try { if (manifestFile.exists()) { FileUtils.forceDelete(manifestFile); } FileUtils.moveFile(backupFile, manifestFile); } catch (IOException e) { // ? log.warn(e.getMessage()); } }
From source file:info.magnolia.integrationtests.uitest.AbstractMagnoliaUITest.java
protected void takeScreenshot(String suffix) { if (driver instanceof TakesScreenshot) { final TakesScreenshot takesScreenshotDriver = (TakesScreenshot) driver; final File file = takesScreenshotDriver.getScreenshotAs(OutputType.FILE); // Replace non url-safe characters with underscores. // Safe: $-_.+!*'() See: http://perishablepress.com/stop-using-unsafe-characters-in-urls/ suffix = suffix.replace(" = ", "-eq-"); suffix = suffix.replaceAll("[\\W\\[\\]\\.\\$\\+!\\*'()]", "_"); suffix = reduceUnderscores(suffix); String dirName = SCREENSHOT_DIR + "/" + testName(); String fileName = String.format("%04d-%s", screenshotIndex++, suffix); // Java somehow thinks it needs to limit file name lengths !? fileName = StringUtils.left(fileName, 250); final File destinationFile = new File(dirName, fileName + ".png"); if (destinationFile.exists()) { // can be existing e.g. from previous test run destinationFile.delete();/*from w w w.j a v a 2s . c om*/ } try { FileUtils.moveFile(file, destinationFile); } catch (IOException e) { log.error(e.getMessage()); // error message might be overlooked so we explicitly fail here. Should assures ppl will immediately realize and fix asap. fail("IOException while moving screenshot " + file + " to " + fileName + " : " + e); } } }