List of usage examples for java.io File renameTo
public boolean renameTo(File dest)
From source file:ch.ivyteam.ivy.maven.TestStartEngine.java
@Test @Ignore//from ww w.j a v a2s . c o m public void engineStartCanFailFast() throws Exception { StartTestEngineMojo mojo = rule.getMojo(); File engineDir = installUpToDateEngineRule.getMojo().getRawEngineDirectory(); File configDir = new File(engineDir, "configuration"); File tmpConfigDir = new File(engineDir, "config.bkp"); configDir.renameTo(tmpConfigDir); StopWatch stopWatch = new StopWatch(); stopWatch.start(); Executor startedProcess = null; try { startedProcess = mojo.startEngine(); fail("Engine start should fail as no configuration directory exists."); } catch (RuntimeException ex) { stopWatch.stop(); long seconds = TimeUnit.SECONDS.convert(stopWatch.getTime(), TimeUnit.MILLISECONDS); assertThat(seconds).describedAs("engine start should fail early if engine config is incomplete") .isLessThanOrEqualTo(20); } finally { kill(startedProcess); FileUtils.deleteDirectory(configDir); tmpConfigDir.renameTo(configDir); } }
From source file:com.esofthead.mycollab.module.file.service.impl.FileRawContentServiceImpl.java
@Override public void renamePath(String oldPath, String newPath) { File file = new File(baseFolder, oldPath); if (file.exists()) { boolean result = file.renameTo(new File(baseFolder + "/" + newPath)); if (!result) { LOG.error("Can not rename old path {} to new path {}", oldPath, newPath); }//from w ww. j a va2 s .c om } else { LOG.error("Can not rename old path {} to new path {} because file is not existed", oldPath, newPath); } }
From source file:com.norconex.commons.lang.file.FileUtil.java
/** * Moves a file to a new file location. This method is different from the * {@link File#renameTo(File)} method in such that: * <ul>/*from ww w . j a v a 2s . c o m*/ * <li>If the target file already exists, it deletes it first.</li> * <li>If target file deletion does not work, it will try 10 times, * waiting 1 second between each try to give a chance to whatever * OS lock on the file to go.</li> * <li>It throws a IOException if the move failed (as opposed to fail * silently).</li> * </ul> * @param sourceFile source file to move * @param targetFile target destination * @throws IOException cannot move file. */ public static void moveFile(File sourceFile, File targetFile) throws IOException { if (!isFile(sourceFile)) { throw new IOException("Source file is not a file or is not valid: " + sourceFile); } if (targetFile == null || targetFile.exists() && !targetFile.isFile()) { throw new IOException("Target file is not a file or is not valid: " + targetFile); } int failure = 0; Exception ex = null; while (failure < MAX_FILE_OPERATION_ATTEMPTS) { if (targetFile.exists() && !targetFile.delete() || !sourceFile.renameTo(targetFile)) { failure++; Sleeper.sleepSeconds(1); continue; } break; } if (failure >= MAX_FILE_OPERATION_ATTEMPTS) { throw new IOException("Could not move \"" + sourceFile + "\" to \"" + targetFile + "\".", ex); } }
From source file:org.ala.spatial.web.services.DownloadController.java
private static void fixAlocFiles(String pid, File dir) { try {/*from ww w .j av a 2 s .co m*/ File tmpdir = new File(dir.getParent() + "/temp/" + pid); //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir)); FileUtils.copyDirectory(dir, tmpdir); //File grd = new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd"); //File grdnew = new File(tmpdir.getAbsolutePath() + "/classfication.grd"); //File gri = new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri"); //File grinew = new File(tmpdir.getAbsolutePath() + "/classfication.gri"); File asc = new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc"); File ascnew = new File(tmpdir.getAbsolutePath() + "/classfication.asc"); File prj = new File(tmpdir.getAbsolutePath() + "/" + pid + ".prj"); File prjnew = new File(tmpdir.getAbsolutePath() + "/classfication.prj"); File png = new File(tmpdir.getAbsolutePath() + "/aloc.png"); File pngnew = new File(tmpdir.getAbsolutePath() + "/classfication.png"); File pgw = new File(tmpdir.getAbsolutePath() + "/aloc.pgw"); File pgwnew = new File(tmpdir.getAbsolutePath() + "/classfication.pgw"); File log = new File(tmpdir.getAbsolutePath() + "/aloc.log"); File lognew = new File(tmpdir.getAbsolutePath() + "/classfication.log"); //grd.renameTo(grdnew); //gri.renameTo(grinew); asc.renameTo(ascnew); prj.renameTo(prjnew); png.renameTo(pngnew); pgw.renameTo(pgwnew); log.renameTo(lognew); (new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc.zip")).delete(); (new File(tmpdir.getAbsolutePath() + "/" + pid + ".sld")).delete(); (new File(tmpdir.getAbsolutePath() + "/aloc.pngextents.txt")).delete(); (new File(tmpdir.getAbsolutePath() + "/aloc.prj")).delete(); (new File(tmpdir.getAbsolutePath() + "/t_aloc.tif")).delete(); (new File(tmpdir.getAbsolutePath() + "/t_aloc.png")).delete(); (new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd")).delete(); (new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri")).delete(); } catch (Exception e) { System.out.println("Unable to fix Classification files"); e.printStackTrace(System.out); } }
From source file:com.greenline.guahao.biz.manager.storage.impl.DefaultStorageManagerImpl.java
@Override public boolean rename(String path, String newPath) { File file = new File(rootDirectory + path); File dest = new File(rootDirectory + newPath); return file.renameTo(dest); }
From source file:maspack.fileutil.SafeFileUtils.java
/** * Moves a file./* w w w. ja v a2 s.c o m*/ * <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} * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file * @since 1.4 */ public static void moveFile(File srcFile, File destFile, int options) 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.isDirectory()) { throw new IOException("Destination '" + destFile + "' is a directory"); } if (destFile.exists()) { destFile.delete(); // try to delete destination before move } boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile, destFile, options); if (!srcFile.delete()) { deleteQuietly(destFile); throw new IOException( "Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } }
From source file:org.shareok.data.kernel.api.services.ServiceUtil.java
public static String executeCommandLineTask(String taskId, String taskType, String data) throws InvalidCommandLineArgumentsException, JSONException, IOException { BufferedWriter loggingForUserFileInfoFileWr = null; BufferedWriter onputFileInfoFileWr = null; String message;//from w ww . ja va2s.c o m String startDate; String endDate; String outputFilePath = null; Integer compare; try { loggingForUserFileInfoFileWr = new BufferedWriter( new FileWriter(DataHandlersUtil.getLoggingForUserFilePath(taskId, taskType), true)); if (DocumentProcessorUtil.isEmptyString(taskId)) { message = "The data argument is null or empty task ID!"; throw new InvalidCommandLineArgumentsException(message); } if (DocumentProcessorUtil.isEmptyString(taskType)) { message = "The data argument does not specify task type!"; throw new InvalidCommandLineArgumentsException(message); } if (DocumentProcessorUtil.isEmptyString(data)) { message = "The data provided for execution of the task is empty!\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } DataHandlersUtil.CURRENT_TASK_TYPE = taskType; JSONObject dataObj = new JSONObject(data); switch (taskType) { case "journal-search": String publisher = dataObj.getString("publisher"); DataHandlersUtil.CURRENT_TASK_ID = taskId; startDate = dataObj.getString("startDate"); endDate = dataObj.getString("endDate"); String affiliate = dataObj.getString("affiliate"); loggingForUserFileInfoFileWr.write("Task information:\n"); loggingForUserFileInfoFileWr.write("Search publications at " + publisher + " between " + startDate + " and " + endDate + " by authors at " + affiliate + ".\n"); loggingForUserFileInfoFileWr.flush(); if (DocumentProcessorUtil.isEmptyString(publisher) || DocumentProcessorUtil.isEmptyString(taskId) || DocumentProcessorUtil.isEmptyString(startDate) || DocumentProcessorUtil.isEmptyString(endDate) || DocumentProcessorUtil.isEmptyString(affiliate)) { message = "Cannot get specific information such as publisher, start date, end date, and/or author affiliation to execute the task.\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } compare = DataHandlersUtil.datesCompare(startDate, endDate); if (compare == null) { message = "Cannot parse the start date or the end date!\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } else if (compare > 0) { message = "The start date is later than the end date!\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } try { DspaceJournalDataService serviceObj = ServiceUtil .getDspaceJournalDataServInstanceByPublisher(publisher); if (null == serviceObj) { loggingForUserFileInfoFileWr .write("The program has internal error, please contact relative personnel.\n"); onputFileInfoFileWr.write("Cannot get the service bean from task type: " + taskType); return null; } String articlesData = serviceObj.getApiResponseByDatesAffiliate(startDate, endDate, affiliate); if (!DocumentProcessorUtil.isEmptyString(articlesData)) { articlesData = articlesData.replace("", "'"); outputFilePath = DataHandlersUtil.getTaskFileFolderPath(taskId, taskType) + File.separator + startDate + "_" + endDate + ".json"; File outputFile = new File(outputFilePath); if (!outputFile.exists()) { outputFile.createNewFile(); } DocumentProcessorUtil.outputStringToFile(articlesData, outputFilePath); System.out.println("article data = " + articlesData); loggingForUserFileInfoFileWr .write("The journal search task has been completed sucessfully.\n"); } else { loggingForUserFileInfoFileWr .write("The program has internal error, please contact relative personnel.\n"); System.out.println( "The " + taskType + " task id=" + taskId + " cannot retrieve the article data!"); } } catch (Exception ex) { loggingForUserFileInfoFileWr .write("The program has internal error, please contact relative personnel.\n"); logger.error("Cannot complete the " + taskType + " with id=" + taskId, ex); } // articlesData = articlesData.replaceAll("'", "\\\\\\'"); break; case "journal-saf": String[] dois; DataHandlersUtil.CURRENT_TASK_ID = taskId; startDate = dataObj.getString("startDate"); endDate = dataObj.getString("endDate"); dois = dataObj.getString("dois").split(";"); if (DocumentProcessorUtil.isEmptyString(startDate) || DocumentProcessorUtil.isEmptyString(endDate) || null == dois || dois.length == 0) { message = "Cannot get specific information such as publication DOI, start date, and/or end date to execute the task.\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } loggingForUserFileInfoFileWr.write("Task information:\n"); loggingForUserFileInfoFileWr .write("Generate DSpace SAF packge for publications with DOIs in " + Arrays.toString(dois) + " which are published between " + startDate + " and " + endDate + ".\n"); loggingForUserFileInfoFileWr.flush(); compare = DataHandlersUtil.datesCompare(startDate, endDate); if (compare == null) { message = "Cannot parse the start date or the end date!\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } else if (compare > 0) { message = "The start date is later than the end date!\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } try { outputFilePath = ServiceUtil.generateDspaceSafPackagesByDois(dois, startDate, endDate); if (outputFilePath.startsWith("error")) { message = "The DOI provided is not valid: " + outputFilePath + "\n"; System.out.println(message); loggingForUserFileInfoFileWr.write(message); throw new ErrorDspaceApiResponseException(message); } else if (null == outputFilePath) { loggingForUserFileInfoFileWr .write("The program has internal error, please contact relative personnel.\n"); throw new ErrorDspaceApiResponseException("Cannot get null saf path!"); } else { loggingForUserFileInfoFileWr.write("safPath=" + outputFilePath + "\n"); loggingForUserFileInfoFileWr.write("The SAF package has been prepared sucessfully.\n"); System.out.println("The SAF package has been stored at path=" + outputFilePath); } } catch (Exception ex) { logger.error(ex); loggingForUserFileInfoFileWr .write("The program has internal error, please contact relative personnel.\n"); ex.printStackTrace(); } break; case "journal-import": try { DataHandlersUtil.CURRENT_TASK_ID = taskId; outputFilePath = ShareokdataManager.getDspaceCommandLineTaskOutputPath() + "_" + DataHandlersUtil.getCurrentTimeString() + "_" + taskType + "_" + taskId + ".txt"; String safPath = dataObj.getString("safPath"); String collectionHandle = dataObj.getString("collectionHandle"); String dspaceApiUrl = dataObj.getString("dspaceApiUrl"); if (DocumentProcessorUtil.isEmptyString(safPath) || DocumentProcessorUtil.isEmptyString(collectionHandle) || DocumentProcessorUtil.isEmptyString(dspaceApiUrl)) { message = "Cannot get specific information such as SAF package path, collection handle, and/or DSpace REST API url to execute the task.\n"; loggingForUserFileInfoFileWr.write(message); throw new InvalidCommandLineArgumentsException(message); } loggingForUserFileInfoFileWr.write("Task information:\n"); loggingForUserFileInfoFileWr.write("Import DSpace SAF packge into collection: " + collectionHandle + " with DSPace REST API URL=" + dspaceApiUrl + "\n"); loggingForUserFileInfoFileWr.flush(); DspaceRestServiceImpl ds = (DspaceRestServiceImpl) getDataService("rest-import-dspace"); ds.getHandler().setReportFilePath( DataHandlersUtil.getJobReportPath("cli-import-dspace-" + taskType, taskId) + File.separator + taskId + "-report.txt"); ds.loadItemsFromSafPackage(safPath, collectionHandle, dspaceApiUrl); } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); } break; case "saf-build": try { loggingForUserFileInfoFileWr.write("Task information:\n"); String csvPath = dataObj.getString("csvPath"); // The full path of the csv file String extension = DocumentProcessorUtil.getFileExtension(csvPath); if (null == extension || !extension.contains("csv")) { throw new NonCsvFileException("The uploaded file is not a CSV file!"); } loggingForUserFileInfoFileWr .write("Generate a SAF package with metadata file at " + csvPath + ".\n"); loggingForUserFileInfoFileWr.write("Start generating...\n"); SAFPackage safPackageInstance = new SAFPackage(); safPackageInstance.processMetaPack(csvPath, true); String csvDirectoryPath = DocumentProcessorUtil.getFileContainerPath(csvPath); File csv = new File(csvPath); File safPackage = new File(csvDirectoryPath + File.separator + "SimpleArchiveFormat.zip"); File newPackage = null; if (safPackage.exists()) { newPackage = new File(csvDirectoryPath + File.separator + DocumentProcessorUtil.getFileNameWithoutExtension(csv.getName()) + ".zip"); if (!newPackage.exists()) { safPackage.renameTo(newPackage); } else { throw new FileAlreadyExistsException("The zip file of the SAF package already exists!"); } } File safPackageFolder = new File(csvDirectoryPath + File.separator + "SimpleArchiveFormat"); if (safPackageFolder.exists()) { FileUtils.deleteDirectory(safPackageFolder); } if (null != newPackage) { outputFilePath = safPackage.getAbsolutePath(); loggingForUserFileInfoFileWr .write("The new SAF package path is: \nsafPath=[\"" + outputFilePath + "\"]\n"); return outputFilePath; } else { loggingForUserFileInfoFileWr.write("The new SAF package generation failed.\n"); return null; } } catch (IOException | FileAlreadyExistsException | NonCsvFileException ex) { logger.error(ex.getMessage()); loggingForUserFileInfoFileWr.write("Error:" + ex.getMessage() + "\n"); loggingForUserFileInfoFileWr.flush(); } default: throw new InvalidCommandLineArgumentsException("The command line task type is valid!"); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (null != loggingForUserFileInfoFileWr) { try { loggingForUserFileInfoFileWr.flush(); loggingForUserFileInfoFileWr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return outputFilePath; }
From source file:com.lxd.client.monitor.MonitorDir.java
private boolean fileCanRead(File file) { if (file.renameTo(file)) { return true; } else {//from w ww . j a va 2 s . c o m return false; } }
From source file:net.sourceforge.vulcan.cvs.CvsProjectConfigurator.java
@SuppressWarnings("unchecked") public void download(File target) throws RepositoryException, IOException { openConnection();/*from w w w . j a va 2 s . com*/ final File exportDir = new File(target.getParentFile(), "cvstmp"); try { final Client client = new Client(this.connection, new StandardAdminHandler()); final ExportCommand cmd = new ExportCommand(); client.setLocalPath(exportDir.getParent()); cmd.setModules(new String[] { file }); cmd.setExportByRevision(tag); cmd.setExportDirectory(exportDir.getName()); cmd.setRecursive(false); client.executeCommand(cmd, options); final Collection<File> files = FileUtils.listFiles(exportDir, null, false); if (files.size() != 1) { throw new RepositoryException("cvs.erorrs.export.failed", null, files.size()); } final File source = files.iterator().next(); if (!source.renameTo(target)) { FileUtils.copyFile(source, target); } } catch (CommandAbortedException e) { throw new RepositoryException(e); } catch (CommandException e) { throw new RepositoryException(e); } catch (AuthenticationException e) { throw new AuthenticationRequiredRepositoryException(cvsRoot.getUserName()); } finally { connection.close(); FileUtils.deleteDirectory(exportDir); } }
From source file:com.cyberway.issue.io.WriterPool.java
public void invalidateFile(WriterPoolMember f) throws IOException { try {/*from w ww .j a v a 2s. c o m*/ this.pool.invalidateObject(f); } catch (Exception e) { // Convert exception. throw new IOException(e.getMessage()); } // It'll have been closed. Rename with an '.invalid' suffix so it // gets attention. File file = f.getFile(); file.renameTo(new File(file.getAbsoluteFile() + WriterPoolMember.INVALID_SUFFIX)); }