List of usage examples for java.nio.file Files move
public static Path move(Path source, Path target, CopyOption... options) throws IOException
From source file:com.kamike.misc.FsUtils.java
public static synchronized boolean moveFile(String src, String dst) { boolean ret = true; try {/* w ww .jav a 2 s. c om*/ Path source = Paths.get(src); Path target = Paths.get(dst); Files.move(source, target, REPLACE_EXISTING); ret = true; } catch (IOException ex) { Logger.getLogger(FsUtils.class.getName()).log(Level.SEVERE, null, ex); ret = false; } return ret; }
From source file:org.xwiki.job.internal.JobStatusSerializer.java
/** * @param status the status to serialize * @param file the file to serialize the status to * @throws IOException when failing to serialize the status *//*from ww w. j a v a2s. co m*/ public void write(JobStatus status, File file) throws IOException { File tempFile = File.createTempFile(file.getName(), ".tmp"); FileOutputStream stream = FileUtils.openOutputStream(tempFile); try { write(status, stream); } finally { IOUtils.closeQuietly(stream); } // Copy the file in it's final destination file.mkdirs(); Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:org.wisdom.maven.utils.BundlePackager.java
/** * Creates the bundle.//ww w. j a va 2 s. c om * * @param basedir the project's base directory * @param output the output file * @throws IOException occurs when the bundle cannot be built correctly. */ public static void bundle(File basedir, File output) throws IOException { Properties properties = new Properties(); // Loads the properties inherited from Maven. readMavenProperties(basedir, properties); // Loads the properties from the BND file. boolean provided = readInstructionsFromBndFiles(properties, basedir); if (!provided) { // No bnd files, set default valued populatePropertiesWithDefaults(basedir, properties); } // Integrate custom headers added by other plugins. mergeExtraHeaders(basedir, properties); // Instruction loaded, start the build sequence. final Jar[] jars = computeClassPath(basedir); final Set<String> elements = computeClassPathElement(basedir); File bnd = null; File ipojo = null; try { Builder builder = getOSGiBuilder(basedir, properties, jars); builder.build(); reportErrors("BND ~> ", builder.getWarnings(), builder.getErrors()); bnd = File.createTempFile("bnd-", ".jar"); ipojo = File.createTempFile("ipojo-", ".jar"); builder.getJar().write(bnd); } catch (Exception e) { throw new IOException("Cannot build the OSGi bundle", e); } Classpath classpath = new Classpath(elements); Pojoization pojoization = new Pojoization(); pojoization.pojoization(bnd, ipojo, new File(basedir, "src/main/resources"), classpath.createClassLoader()); reportErrors("iPOJO ~> ", pojoization.getWarnings(), pojoization.getErrors()); Files.move(Paths.get(ipojo.getPath()), Paths.get(output.getPath()), StandardCopyOption.REPLACE_EXISTING); }
From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java
public static void appendToEndOfLine(Path targetDumpFile, String toAppend) throws Exception { Path tmp = Files.createTempFile(null, null); try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(targetDumpFile), CSV_DUMP_FORMAT)) { try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(tmp), CSV_DUMP_FORMAT)) { csvParser.forEach(record -> { List<String> newRecord = new ArrayList<>(); record.forEach(val -> newRecord.add(val)); newRecord.add(toAppend); try { csvPrinter.printRecord(newRecord); } catch (IOException e) { throw new RuntimeException("Error appending to EOL", e); }/*from ww w. jav a2 s .co m*/ }); } } Files.move(tmp, targetDumpFile, StandardCopyOption.REPLACE_EXISTING); }
From source file:es.ucm.fdi.storage.business.entity.StorageObject.java
public void save(InputStream input) throws IOException { Path file = root.resolve(UUID.randomUUID().toString()); try (FileOutputStream out = new FileOutputStream(file.toFile())) { MessageDigest sha2sum = MessageDigest.getInstance("SHA-256"); byte[] dataBytes = new byte[4 * 1024]; int nread = 0; long length = 0; while ((nread = input.read(dataBytes)) != -1) { sha2sum.update(dataBytes, 0, nread); out.write(dataBytes, 0, nread); length += nread;//from www . j ava2 s . c om } this.internalName = toHexString(sha2sum.digest()); this.length = length; out.close(); String folder = internalName.substring(0, 2); Path parent = Files.createDirectories(root.resolve(folder)); Files.move(file, parent.resolve(internalName), StandardCopyOption.REPLACE_EXISTING); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Cant save file", nsae); } }
From source file:org.nuxeo.ecm.platform.ui.web.util.files.FileUtils.java
/** * Creates a Blob from a {@link Part}./*from w w w. j a v a 2 s. c o m*/ * <p> * Attempts to capture the underlying temporary file, if one exists. This needs to use reflection to avoid having * dependencies on the application server. * * @param part the servlet part * @return the blob * @since 7.2 */ public static Blob createBlob(Part part) throws IOException { Blob blob = null; try { // part : org.apache.catalina.core.ApplicationPart // part.fileItem : org.apache.tomcat.util.http.fileupload.disk.DiskFileItem // part.fileItem.isInMemory() : false if on disk // part.fileItem.getStoreLocation() : java.io.File Field fileItemField = part.getClass().getDeclaredField("fileItem"); fileItemField.setAccessible(true); Object fileItem = fileItemField.get(part); if (fileItem != null) { Method isInMemoryMethod = fileItem.getClass().getDeclaredMethod("isInMemory"); boolean inMemory = ((Boolean) isInMemoryMethod.invoke(fileItem)).booleanValue(); if (!inMemory) { Method getStoreLocationMethod = fileItem.getClass().getDeclaredMethod("getStoreLocation"); File file = (File) getStoreLocationMethod.invoke(fileItem); if (file != null) { // move the file to a temporary blob we own blob = Blobs.createBlobWithExtension(null); Files.move(file.toPath(), blob.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING); } } } } catch (ReflectiveOperationException | SecurityException | IllegalArgumentException e) { // unknown Part implementation } if (blob == null) { // if we couldn't get to the file, use the InputStream blob = Blobs.createBlob(part.getInputStream()); } blob.setMimeType(part.getContentType()); blob.setFilename(retrieveFilename(part)); return blob; }
From source file:org.geowebcache.util.FileUtils.java
/** * Utility method for renaming Files using Java 7 {@link Files}.move() method * which provides an atomical file renaming. If an exception occurred during the * renaming, the method will fallback to the old File().renameTo() method and * will log a Message. //from w w w .ja va2 s . co m * * @return a boolean indicating if the rename operation has succeded */ public static boolean renameFile(File src, File dst) { // Renaming result initialization boolean renamed = false; // 1) try with Java 7 Files.move Path srcPath = Paths.get(src.toURI()); Path dstPath = Paths.get(dst.toURI()); Path moved = null; try { // Execute renaming moved = Files.move(srcPath, dstPath, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e) { // Exception occurred falling back to the old renameTo if (log.isDebugEnabled()) { log.debug( "An error occurred when executing atomic file renaming. Falling back to the old File.renameTo() method", e); } } // 2) Check if succeeded. If failed, falling back to old renameTo if (moved == null || !Files.exists(moved)) { renamed = src.renameTo(dst); } else { renamed = true; } return renamed; }
From source file:org.structr.media.SetMetadataProcess.java
@Override public Void processExited(int exitCode) { if (exitCode == 0) { try (final Tx tx = StructrApp.getInstance(securityContext).tx()) { // move converted file into place final java.io.File diskFile = new java.io.File(outputFileName + "." + fileExtension); final java.io.File dstFile = new java.io.File(outputFileName); if (diskFile.exists()) { Files.move(diskFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING); FileHelper.updateMetadata(inputVideo); }// w w w. j av a 2s . co m tx.success(); } catch (FrameworkException | IOException fex) { fex.printStackTrace(); } } return null; }
From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java
@Async public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) { Long queueId = jobQueueInfo.getId(); String fileName = jobQueueInfo.getFileName() + ".txt"; String jsonFileName = jobQueueInfo.getFileName() + ".json"; String commands = jobQueueInfo.getCommands(); String tmpDirectory = jobQueueInfo.getTmpDirectory(); String outputDirectory = jobQueueInfo.getOutputDirectory(); List<String> cmdList = new LinkedList<>(); cmdList.addAll(Arrays.asList(commands.split(";"))); cmdList.add("--out"); cmdList.add(tmpDirectory);/*from w w w .ja va 2s . c o m*/ StringBuilder sb = new StringBuilder(); cmdList.forEach(cmd -> { sb.append(cmd); sb.append(" "); }); LOGGER.info("Algorithm command: " + sb.toString()); String errorFileName = String.format("error_%s", fileName); Path error = Paths.get(tmpDirectory, errorFileName); Path errorDest = Paths.get(outputDirectory, errorFileName); Path src = Paths.get(tmpDirectory, fileName); Path dest = Paths.get(outputDirectory, fileName); Path json = Paths.get(tmpDirectory, jsonFileName); Path jsonDest = Paths.get(outputDirectory, jsonFileName); try { ProcessBuilder pb = new ProcessBuilder(cmdList); pb.redirectError(error.toFile()); Process process = pb.start(); //Get process Id Long pid = Processes.processId(process); JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId); LOGGER.info("Set Job's pid to be: " + pid); queuedJobInfo.setPid(pid); jobQueueInfoService.saveJobIntoQueue(queuedJobInfo); process.waitFor(); if (process.exitValue() == 0) { LOGGER.info(String.format("Moving txt file %s to %s", src, dest)); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); LOGGER.info(String.format("Moving json file %s to %s", json, dest)); Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(error); } else { LOGGER.info(String.format("Deleting tmp txt file %s", src)); Files.deleteIfExists(src); LOGGER.info(String.format("Moving error file %s to %s", error, errorDest)); Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException | InterruptedException exception) { LOGGER.error("Algorithm did not run successfully.", exception); } LOGGER.info("Delete Job ID from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); return new AsyncResult<>(null); }
From source file:org.structr.media.ConverterProcess.java
@Override public VideoFile processExited(int exitCode) { final App app = StructrApp.getInstance(securityContext); if (exitCode == 0) { try (final Tx tx = app.tx()) { // move converted file into place final java.io.File diskFile = new java.io.File(outputFileName + fileExtension); final java.io.File dstFile = new java.io.File(outputFileName); if (diskFile.exists()) { Files.move(diskFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING); FileHelper.updateMetadata(newFile); // create link between the two videos newFile.setProperty(StructrApp.key(VideoFile.class, "originalVideo"), inputFile); }// ww w .j av a 2 s .com tx.success(); } catch (FrameworkException | IOException fex) { logger.warn("", fex); } } else { // delete file, conversion has failed try (final Tx tx = app.tx()) { app.delete(newFile); tx.success(); } catch (FrameworkException fex) { logger.warn("", fex); } } return newFile; }