List of usage examples for java.io File renameTo
public boolean renameTo(File dest)
From source file:de.brazzy.nikki.model.ImageWriter.java
/** * causes all image data to be written to the file's EXIF headers. *///ww w . j a v a2s.co m public void saveImage() throws Exception { if (createException != null) { throw createException; } writeTitle(); writeDescription(); writeTime(); writeExport(); writeGPS(); writeThumbnail(); File tmpFile = File.createTempFile("nikki", "tmp", new File(file.getParent())); InputStream fip = new BufferedInputStream(new FileInputStream(file)); OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile)); llj.refreshAppx(); llj.xferInfo(fip, out, LLJTran.REPLACE, LLJTran.RETAIN); llj.freeMemory(); fip.close(); out.close(); if (!file.delete()) { throw new IllegalStateException(); } if (!tmpFile.renameTo(file)) { throw new IllegalStateException(); } }
From source file:com.vaadin.tests.tb3.ScreenshotTB3Test.java
protected void compareScreen(WebElement element, String identifier) throws IOException { if (identifier == null || identifier.isEmpty()) { throw new IllegalArgumentException("Empty identifier not supported"); }//from w ww. j ava 2 s . c o m File mainReference = getScreenshotReferenceFile(identifier); List<File> referenceFiles = findReferenceAndAlternatives(mainReference); List<File> failedReferenceFiles = new ArrayList<>(); for (File referenceFile : referenceFiles) { boolean match = false; if (element == null) { // Full screen match = testBench(driver).compareScreen(referenceFile); } else { // Only the element match = customTestBench(driver).compareScreen(element, referenceFile); } if (match) { // There might be failure files because of retries in TestBench. deleteFailureFiles(getErrorFileFromReference(referenceFile)); break; } else { failedReferenceFiles.add(referenceFile); } } File referenceToKeep = null; if (failedReferenceFiles.size() == referenceFiles.size()) { // Ensure we use the correct browser version (e.g. if running IE11 // and only an IE 10 reference was available, then mainReference // will be for IE 10, not 11) String originalName = getScreenshotReferenceName(identifier); File exactVersionFile = new File(originalName); if (!exactVersionFile.equals(mainReference)) { // Rename png+html to have the correct version File correctPng = getErrorFileFromReference(exactVersionFile); File producedPng = getErrorFileFromReference(mainReference); File correctHtml = htmlFromPng(correctPng); File producedHtml = htmlFromPng(producedPng); producedPng.renameTo(correctPng); producedHtml.renameTo(correctHtml); referenceToKeep = exactVersionFile; screenshotFailures.add(exactVersionFile.getName()); } else { // All comparisons failed, keep the main error image + HTML screenshotFailures.add(mainReference.getName()); referenceToKeep = mainReference; } } // Remove all PNG/HTML files we no longer need (failed alternative // references or all error files (PNG/HTML) if comparison succeeded) for (File failedAlternative : failedReferenceFiles) { File failurePng = getErrorFileFromReference(failedAlternative); if (failedAlternative != referenceToKeep) { // Delete png + HTML deleteFailureFiles(failurePng); } } if (referenceToKeep != null) { File errorPng = getErrorFileFromReference(referenceToKeep); enableAutoswitch(new File(errorPng.getParentFile(), errorPng.getName() + ".html")); } }
From source file:com.ephesoft.dcma.util.PDFUtil.java
/** * The <code>getSelectedPdfFile</code> method is used to limit the file * to the page limit given.//from w w w .ja v a 2s . c om * * @param pdfFile {@link File} pdf file from which limit has to be applied * @param pageLimit int * @throws IOException if file is not found * @throws DocumentException if document cannot be created */ public static void getSelectedPdfFile(final File pdfFile, final int pageLimit) throws IOException, DocumentException { PdfReader reader = null; Document document = null; PdfContentByte contentByte = null; PdfWriter writer = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; File newFile = null; if (null != pdfFile && pdfFile.exists()) { try { document = new Document(); fileInputStream = new FileInputStream(pdfFile); String name = pdfFile.getName(); final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT); name = name.substring(0, indexOf); final String finalPath = pdfFile.getParent() + File.separator + name + System.currentTimeMillis() + IUtilCommonConstants.EXTENSION_PDF; newFile = new File(finalPath); fileOutputStream = new FileOutputStream(finalPath); writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); contentByte = writer.getDirectContent(); reader = new PdfReader(fileInputStream); for (int i = 1; i <= pageLimit; i++) { document.newPage(); // import the page from source pdf final PdfImportedPage page = writer.getImportedPage(reader, i); // add the page to the destination pdf contentByte.addTemplate(page, 0, 0); page.closePath(); } } finally { closePassedStream(reader, document, contentByte, writer, fileInputStream, fileOutputStream); } if (pdfFile.delete() && null != newFile) { newFile.renameTo(pdfFile); } else { if (null != newFile) { newFile.delete(); } } } }
From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java
/** * @param req//from w ww. j av a 2 s .c om * @param resp * @throws ServletException * @throws IOException */ public void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { System.out.println("================================="); String fileName = req.getHeader(HttpLargeFileTransfer.FILE_NAME_HEADER); if (fileName == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Filename not specified"); return; } String clientID = req.getHeader(HttpLargeFileTransfer.CLIENT_ID_HEADER); if (null == clientID) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Client ID"); return; } String serviceNumber = req.getHeader(HttpLargeFileTransfer.SERVICE_NUMBER); if (null == serviceNumber) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Service Number"); return; } String databaseName = StringUtils.replace(serviceNumber, ".", "_"); int numChunks = req.getIntHeader(HttpLargeFileTransfer.FILE_CHUNK_COUNT_HEADER); int chunkCnt = req.getIntHeader(HttpLargeFileTransfer.FILE_CHUNK_HEADER); if (numChunks == -1 || chunkCnt == -1) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing chunk information"); return; } if (chunkCnt == 0) { // check permission to create file here } OutputStream fos = null; if (numChunks == 1) { fos = new FileOutputStream(fileName); // create } else { fos = new FileOutputStream(getTempFile(clientID), (chunkCnt > 0)); // append } InputStream fis = req.getInputStream(); byte[] buf = new byte[BUFFER_SIZE]; int totalLen = 0; while (true) { int len = fis.read(buf); if (len > 0) { totalLen += len; fos.write(buf, 0, len); } else if (len == -1) { break; } } fis.close(); fos.close(); File destFile = new File(fileName); boolean isOK = true; if (numChunks > 1 && chunkCnt == numChunks - 1) { File tmpFile = new File(getTempFile(clientID)); if (destFile.exists()) { destFile.delete(); } if (!tmpFile.renameTo(destFile)) { isOK = false; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create file"); return; } } if (isOK) { String fullDestPath = destFile + ".sql"; if (uncompressFile(destFile.getAbsolutePath(), fullDestPath)) { //File newFile = new File(fullDestPath); databaseName = "db"; //System.out.println("Uncompressed:["+fullDestPath+"] size: ["+newFile.length()+"] database["+databaseName+"]"); MySQLBackupService backupService = new MySQLBackupService(); if (backupService.doRestore(fullDestPath, "/usr/local/mysql/bin/mysql", databaseName, "root", "root")) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error restoring"); } } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error decompressing"); } }
From source file:it.geosolutions.tools.io.CopyTreeTest.java
@Test public void rebaseTest() throws Exception { LOGGER.info("BEGIN: rebaseTest"); // rebase a file LOGGER.info("Before: " + testFile); File srcMount = TestData.file(this, "."); File rebasedFile = Path.rebaseFile(srcMount, destMount, testFile); rebasedFile.getParentFile().mkdirs(); Assert.assertTrue(testFile.renameTo(rebasedFile)); LOGGER.info("After: " + rebasedFile); // TEST: File is not in the mount point dir Assert.assertFalse(testFile.exists()); // move it back LOGGER.info("Before: " + rebasedFile); testFile = Path.rebaseFile(destMount, srcMount, rebasedFile); testFile.getParentFile().mkdirs();//w w w.ja v a 2 s. c o m Assert.assertTrue(rebasedFile.renameTo(testFile)); LOGGER.info("After: " + testFile.getAbsolutePath()); // TEST: File is not in the mount point dir Assert.assertFalse(rebasedFile.exists()); LOGGER.info("END: rebaseTest"); }
From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java
@Override public void convert(File v2SegmentDirectory) throws Exception { Preconditions.checkNotNull(v2SegmentDirectory, "Segment directory should not be null"); Preconditions.checkState(v2SegmentDirectory.exists() && v2SegmentDirectory.isDirectory(), "Segment directory: " + v2SegmentDirectory.toString() + " must exist and should be a directory"); LOGGER.info("Converting segment: {} to v3 format", v2SegmentDirectory); // check existing segment version SegmentMetadataImpl v2Metadata = new SegmentMetadataImpl(v2SegmentDirectory); SegmentVersion oldVersion = SegmentVersion.valueOf(v2Metadata.getVersion()); Preconditions.checkState(oldVersion != SegmentVersion.v3, "Segment {} is already in v3 format but at wrong path", v2Metadata.getName()); Preconditions.checkArgument(oldVersion == SegmentVersion.v1 || oldVersion == SegmentVersion.v2, "Can not convert segment version: {} at path: {} ", oldVersion, v2SegmentDirectory); deleteStaleConversionDirectories(v2SegmentDirectory); File v3TempDirectory = v3ConversionTempDirectory(v2SegmentDirectory); setDirectoryPermissions(v3TempDirectory); createMetadataFile(v2SegmentDirectory, v3TempDirectory); copyCreationMetadata(v2SegmentDirectory, v3TempDirectory); copyIndexData(v2SegmentDirectory, v2Metadata, v3TempDirectory); File newLocation = SegmentDirectoryPaths.segmentDirectoryFor(v2SegmentDirectory, SegmentVersion.v3); LOGGER.info("v3 segment location for segment: {} is {}", v2Metadata.getName(), newLocation); v3TempDirectory.renameTo(newLocation); }
From source file:de.citec.sc.index.ProcessAnchorFile.java
public static void run(String filePath) { try {// w ww . j a v a 2 s . c om File file = new File("new.ttl"); // if file doesnt exists, then create it if (file.exists()) { file.delete(); file.createNewFile(); } if (!file.exists()) { file.createNewFile(); } BufferedReader wpkg = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); String line = ""; PrintStream ps = new PrintStream("new.ttl", "UTF-8"); while ((line = wpkg.readLine()) != null) { String[] data = line.split("\t"); if (data.length == 3) { String label = data[0]; label = StringEscapeUtils.unescapeJava(label); try { label = URLDecoder.decode(label, "UTF-8"); } catch (Exception e) { } String uri = data[1].replace("http://dbpedia.org/resource/", ""); uri = StringEscapeUtils.unescapeJava(uri); try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (Exception e) { } String f = data[2]; label = label.toLowerCase(); ps.println(label + "\t" + uri + "\t" + f); } } wpkg.close(); ps.close(); File oldFile = new File(filePath); oldFile.delete(); oldFile.createNewFile(); file.renameTo(oldFile); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.cinchapi.concourse.server.plugin.PluginManager.java
/** * Install the plugin bundle located within a zip file to the {@link #home} * directory.//from w ww. ja va 2 s. c om * * @param bundle the path to the plugin bundle */ public void installBundle(String bundle) { String basename = com.google.common.io.Files.getNameWithoutExtension(bundle); String name = null; try { String manifest = ZipFiles.getEntryContent(bundle, basename + File.separator + MANIFEST_FILE); JsonObject json = (JsonObject) new JsonParser().parse(manifest); name = json.get("bundleName").getAsString(); ZipFiles.unzip(bundle, home); File src = new File(home + File.separator + basename); File dest = new File(home + File.separator + name); src.renameTo(dest); Logger.info("Installed the plugins in {} at {}", bundle, dest.getAbsolutePath()); activate(name); } catch (Exception e) { Throwable cause = null; if ((cause = e.getCause()) != null && cause instanceof ZipException) { throw new RuntimeException(bundle + " is not a valid plugin bundle"); } else { if (name != null) { // Likely indicates that there was a problem with // activation, so run uninstall path so things are not in a // weird state uninstallBundle(name); } throw e; // re-throw exception so CLI fails } } }
From source file:io.stallion.asyncTasks.AsyncTaskFilePersister.java
public boolean markFailed(AsyncTask task, Throwable e) { File file = new File(fullFilePathForObj(task)); task.setTryCount(task.getTryCount() + 1); task.setErrorMessage(e.toString() + ExceptionUtils.getStackTrace(e)); if (task.getTryCount() >= 5) { task.setFailedAt(DateUtils.mils()); } else {//from w ww. j a va2 s . com task.setExecuteAt(DateUtils.mils() + ((2 ^ task.getTryCount()) * 1000)); task.setLockedAt(0); task.setLockUuid(""); } File dest = new File(fullFilePathForObj(task)); boolean succeeded = file.renameTo(dest); if (!succeeded) { return false; } persist(task); return true; }