List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java
public void copyTo(String fileId, File destPath, boolean replaceExisting) throws IOException { String filePath = fileIdToPath(fileId); File dataFile = new File(filePath + ".data"); File parentFile = destPath.getParentFile(); if (parentFile != null) Files.createDirectories(parentFile.toPath()); if (replaceExisting) Files.copy(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING); else/*www.j a va 2 s. com*/ Files.copy(dataFile.toPath(), destPath.toPath()); }
From source file:org.transitime.applications.SchemaGenerator.java
/** * Gets rid of the unwanted drop table commands. These aren't needed because * the resulting script is intended only for creating a database, not for * deleting all the data and recreating the tables. * //from w w w . ja va 2s . com * @param outputFilename */ private void trimCruftFromFile(String outputFilename) { // Need to write to a temp file because if try to read and write // to same file things get quite confused. String tmpFileName = outputFilename + "_tmp"; BufferedReader reader = null; BufferedWriter writer = null; try { FileInputStream fis = new FileInputStream(outputFilename); reader = new BufferedReader(new InputStreamReader(fis)); FileOutputStream fos = new FileOutputStream(tmpFileName); writer = new BufferedWriter(new OutputStreamWriter(fos)); String line; while ((line = reader.readLine()) != null) { // Filter out "drop table" commands if (line.contains("drop table")) { // Read in following blank line line = reader.readLine(); // Continue to next line since filtering out drop table commands continue; } // Filter out "drop sequence" oracle commands if (line.contains("drop sequence")) { // Read in following blank line line = reader.readLine(); // Continue to next line since filtering out drop commands continue; } // Filter out the alter table commands where dropping a key or // a constraint if (line.contains("alter table")) { String nextLine = reader.readLine(); if (nextLine.contains("drop")) { // Need to continue reading until process a blank line while (reader.readLine().length() != 0) ; // Continue to next line since filtering out drop commands continue; } else { // It is an "alter table" command but not a "drop". // Therefore need to keep this command. Since read in // two lines need to handle this specially and then // continue writer.write(line); writer.write("\n"); writer.write(nextLine); writer.write("\n"); continue; } } // Line not being filtered so write it to the file writer.write(line); writer.write("\n"); } } catch (IOException e) { System.err.println("Could not trim cruft from file " + outputFilename + " . " + e.getMessage()); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { } } // Move the temp file to the original name try { Files.copy(new File(tmpFileName).toPath(), new File(outputFilename).toPath(), StandardCopyOption.REPLACE_EXISTING); Files.delete(new File(tmpFileName).toPath()); } catch (IOException e) { System.err.println("Could not rename file " + tmpFileName + " to " + outputFilename); } }
From source file:org.eclipse.winery.generators.ia.Generator.java
/** * Generates the IA project.//from w w w . j av a 2 s. com * * @return The ZIP file containing the maven/eclipse project to be * downloaded by the user. */ public File generateProject() { try { Path workingDirPath = this.workingDir.toPath(); Files.createDirectories(workingDirPath); // directory to store the template files to generate the java files from Path javaTemplateDir = workingDirPath.resolve("../java"); Files.createDirectories(javaTemplateDir); // Copy template project and template java files String s = this.getClass().getResource("").getPath(); if (s.contains("jar!")) { Generator.logger.trace("we work on a jar file"); Generator.logger.trace("Location of the current class: {}", s); // we have a jar file // format: file:/location...jar!...path-in-the-jar // we only want to have location :) int excl = s.lastIndexOf("!"); s = s.substring(0, excl); s = s.substring("file:".length()); try (JarFile jf = new JarFile(s);) { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String name = je.getName(); if (name.startsWith(Generator.TEMPLATE_PROJECT_FOLDER + "/") && (name.length() > (Generator.TEMPLATE_PROJECT_FOLDER.length() + 1))) { // strip "template/" from the beginning to have paths without "template" starting relatively from the working dir name = name.substring(Generator.TEMPLATE_PROJECT_FOLDER.length() + 1); if (je.isDirectory()) { // directory found Path dir = workingDirPath.resolve(name); Files.createDirectory(dir); } else { Path file = workingDirPath.resolve(name); try (InputStream is = jf.getInputStream(je);) { Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING); } } } else if (name.startsWith(Generator.TEMPLATE_JAVA_FOLDER + "/") && (name.length() > (Generator.TEMPLATE_JAVA_FOLDER.length() + 1))) { if (!je.isDirectory()) { // we copy the file directly into javaTemplateDir File f = new File(name); Path file = javaTemplateDir.resolve(f.getName()); try (InputStream is = jf.getInputStream(je);) { Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING); } } } } } } else { // we're running in debug mode, we can work on the plain file system File templateProjectDir = new File( this.getClass().getResource("/" + Generator.TEMPLATE_PROJECT_FOLDER).getFile()); FileUtils.copyDirectory(templateProjectDir, this.workingDir); File javaTemplatesDir = new File( this.getClass().getResource("/" + Generator.TEMPLATE_JAVA_FOLDER).getFile()); FileUtils.copyDirectory(javaTemplatesDir, javaTemplateDir.toFile()); } // Create Java Code Folder String[] splitPkg = this.javaPackage.split("\\."); String javaFolderString = this.workingDir.getAbsolutePath() + File.separator + "src" + File.separator + "main" + File.separator + "java"; for (int i = 0; i < splitPkg.length; i++) { javaFolderString += File.separator + splitPkg[i]; } // Copy TEMPLATE_JAVA_ABSTRACT_IA_SERVICE Path templateAbstractIAService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_ABSTRACT_IA_SERVICE); File javaAbstractIAService = new File(javaFolderString + File.separator + "AbstractIAService.java"); Files.createDirectories(javaAbstractIAService.toPath().getParent()); Files.copy(templateAbstractIAService, javaAbstractIAService.toPath(), StandardCopyOption.REPLACE_EXISTING); // Copy and rename TEMPLATE_JAVA_TEMPLATE_SERVICE Path templateJavaService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_TEMPLATE_SERVICE); File javaService = new File(javaFolderString + File.separator + this.name + ".java"); Files.createDirectories(javaService.toPath().getParent()); Files.copy(templateJavaService, javaService.toPath(), StandardCopyOption.REPLACE_EXISTING); this.generateJavaFile(javaService); this.updateFilesRecursively(this.workingDir); return this.packageProject(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.facebook.buck.util.ProjectFilesystemTest.java
@Test public void testCopyToPathWithOptions() throws IOException { InputStream inputStream = new ByteArrayInputStream("hello!".getBytes()); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt")); inputStream = new ByteArrayInputStream("hello again!".getBytes()); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt"), StandardCopyOption.REPLACE_EXISTING); assertEquals("The bytes on disk should match those from the second InputStream.", "hello again!", Files.toString(new File(tmp.getRoot(), "replace_me.txt"), Charsets.UTF_8)); }
From source file:com.bekwam.resignator.commands.UnsignCommand.java
public void copyJAR(String sourceJarFileName, String targetJarFileName) throws CommandExecutionException { Path sourceJarFile = Paths.get(sourceJarFileName); Path targetJarFile = Paths.get(targetJarFileName); try {/* ww w . j a va 2 s .co m*/ Files.copy(sourceJarFile, targetJarFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException exc) { String msg = String.format("can't copy %s to %s", sourceJarFileName, targetJarFileName); logger.error(msg, exc); throw new CommandExecutionException(msg); } }
From source file:org.niord.core.batch.BatchService.java
/** * Starts a new file-based batch job// www . j a v a 2s.c o m * * @param jobName the batch job name */ public long startBatchJobWithDataFile(String jobName, InputStream in, String dataFileName, Map<String, Object> properties) throws IOException { BatchData job = initBatchData(jobName, properties); if (in != null) { job.setDataFileName(dataFileName); Path path = computeBatchJobPath(job.computeDataFilePath()); createDirectories(path.getParent()); Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING); } return startBatchJob(job); }
From source file:com.amazon.alexa.avs.AVSAudioPlayer.java
public void handlePlay(Play play) throws DirectiveHandlingException { AudioItem item = play.getAudioItem(); if (play.getPlayBehavior() == Play.PlayBehavior.REPLACE_ALL) { clearAll();//from w ww. ja va 2 s. c o m } else if (play.getPlayBehavior() == Play.PlayBehavior.REPLACE_ENQUEUED) { clearEnqueued(); } Stream stream = item.getStream(); String streamUrl = stream.getUrl(); String streamId = stream.getToken(); long offset = stream.getOffsetInMilliseconds(); log.info("URL: {}", streamUrl); log.info("StreamId: {}", streamId); log.info("Offset: {}", offset); if (stream.hasAttachedContent()) { try { File tmp = File.createTempFile(UUID.randomUUID().toString(), ".mp3"); tmp.deleteOnExit(); Files.copy(stream.getAttachedContent(), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING); stream.setUrl(tmp.getAbsolutePath()); add(stream); } catch (IOException e) { log.error("Error while saving audio to a file", e); throw new DirectiveHandlingException(ExceptionType.INTERNAL_ERROR, "Error saving attached content to disk, unable to handle Play directive."); } } else { add(stream); } }
From source file:com.book.identification.rest.VolumeResource.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN)//w w w. j a v a 2s . c o m @Path("upload/") public Response upload(@FormDataParam("file") InputStream inputStream) throws Exception { //Save in temporal file File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".temp"); FileUtils.copyInputStreamToFile(inputStream, tempFile); String md5Hex = DigestUtils.md5Hex(FileUtils.openInputStream(tempFile)); java.nio.file.Path path = new File(System.getProperty("user.dir")).toPath().resolve("books"); if (!Files.exists(path)) { Files.createDirectories(path); } java.nio.file.Path filePath = path.resolve(md5Hex); try { Files.copy(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { return Response.serverError().build(); } return Response.ok(md5Hex).build(); }
From source file:org.holodeckb2b.deliverymethod.file.AbstractFileDeliverer.java
/** * Helper method to copy a the payload content to <i>delivery directory</i>. * /* www .ja v a 2 s. c o m*/ * @param p The payload for which the content must be copied * @param msgId The message-id of the message that contains the payload, used for name the file * @return The path where the payload content is now stored * @throws IOException When the payload content could not be copied to the <i>delivery directory</i> */ private Path copyPayloadFile(IPayload p, String msgId) throws IOException { // If payload was external to message, it is not processed by Holodeck B2B, so no content to move if (IPayload.Containment.EXTERNAL == p.getContainment()) return null; // Compose a file name for the payload file, based on msgId and href String plRef = p.getPayloadURI(); plRef = (plRef == null || plRef.isEmpty() ? "body" : plRef); // If this was a attachment the reference is a a MIME Content-id. As these are also quite lengthy we shorten // it to the left part if (plRef.indexOf("@") > 0) plRef = plRef.substring(0, plRef.indexOf("@")); Path sourcePath = Paths.get(p.getContentLocation()); // Try to set nice extension based on MIME Type of payload String mimeType = p.getMimeType(); if (mimeType == null || mimeType.isEmpty()) { // No MIME type given in message, try to detect from content try { mimeType = Utils.detectMimeType(sourcePath.toFile()); } catch (IOException ex) { mimeType = null; } // Unable to detect the MIME Type } String ext = Utils.getExtension(mimeType); Path targetPath = Paths.get(Utils.preventDuplicateFileName(directory + "pl-" + (msgId + "-" + plRef).replaceAll("[^a-zA-Z0-9.-]", "_") + (ext != null ? ext : ""))); try { Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception ex) { // Can not move payload file -> delivery not possible throw new IOException("Unable to deliver message because payload file [" + p.getContentLocation() + "] can not be moved!", ex); } return targetPath.toAbsolutePath(); }
From source file:org.sigmah.server.servlet.ImportServlet.java
/** * Store the uploaded file on the disk and return the identifier of the * file to the user./*from w w w. j a va 2 s .c om*/ * * @param request Http request. * @param response Http response. * @param context Execution context. * @throws FileUploadException If an error occured while reading the http request. * @throws IOException If the file could not be written on the server. */ public void storeFile(final HttpServletRequest request, final HttpServletResponse response, final ServletExecutionContext context) throws FileUploadException, IOException { final HashMap<String, String> properties = new HashMap<String, String>(); final byte[] data; try { data = readFileAndProperties(request, properties); } catch (FileUploadException | IOException ex) { LOG.error("Error while receiving a file containing values.", ex); throw ex; } if (data != null) { // A file has been received final String uniqueFileId = FileServlet.generateUniqueName(); final long length = fileStorageProvider.copy(new ByteArrayInputStream(data), uniqueFileId, StandardCopyOption.REPLACE_EXISTING); if (length > 0) { response.setContentType("text/html"); response.getWriter().write(uniqueFileId); } } }