List of usage examples for java.nio.file Files copy
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
From source file:de.cebitec.readXplorer.differentialExpression.plot.BaySeqGraphicsTopComponent.java
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") { private static final long serialVersionUID = 1L; @Override//from w w w . j av a 2 s . co m public void save(String fileLocation) { Path to = FileSystems.getDefault().getPath(fileLocation, ""); BaySeqAnalysisHandler.Plot selectedPlot = (BaySeqAnalysisHandler.Plot) plotTypeComboBox .getSelectedItem(); if (selectedPlot == BaySeqAnalysisHandler.Plot.MACD) { saveToSVG(fileLocation); } else { Path from = currentlyDisplayed.toPath(); try { Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); messages.setText("SVG image saved to " + outputFile.toString()); } catch (IOException ex) { Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(), currentTimestamp); JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.", JOptionPane.WARNING_MESSAGE); } } } @Override public void open(String fileLocation) { } }; fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG); }
From source file:com.bekwam.mavenpomupdater.MainViewController.java
public void doUpdate() { for (POMObject p : tblPOMS.getItems()) { if (log.isDebugEnabled()) { log.debug("[DO UPDATE] p=" + p.getAbsPath()); }/*from w w w .j a va 2s . co m*/ if (p.getParseError()) { if (log.isDebugEnabled()) { log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath() + " because of a parse error on scanning"); } continue; } if (!p.getUpdate()) { if (log.isDebugEnabled()) { log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath() + " because user excluded it from update"); } continue; } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(p.getAbsPath()); if (p.getParentVersion() != null && p.getParentVersion().length() > 0) { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("//project/parent/version/text()"); Node node = (Node) expression.evaluate(doc, XPathConstants.NODE); if (StringUtils.isNotEmpty(tfNewVersion.getText())) { node.setNodeValue(tfNewVersion.getText()); } else { // editing individual table cells node.setNodeValue(p.getParentVersion()); } } if (p.getVersion() != null && p.getVersion().length() > 0) { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("//project/version/text()"); Node node = (Node) expression.evaluate(doc, XPathConstants.NODE); if (StringUtils.isNotEmpty(tfNewVersion.getText())) { node.setNodeValue(tfNewVersion.getText()); } else { // editing individual table cells node.setNodeValue(p.getVersion()); } } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); String workingFileName = p.getAbsPath() + ".mpu"; FileWriter fw = new FileWriter(workingFileName); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fw); transformer.transform(source, result); fw.close(); Path src = FileSystems.getDefault().getPath(workingFileName); Path target = FileSystems.getDefault().getPath(p.getAbsPath()); Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING); Files.delete(src); } catch (Exception exc) { log.error("error updating poms", exc); } } if (StringUtils.isNotEmpty(tfRootDir.getText())) { if (log.isDebugEnabled()) { log.debug("[DO UPDATE] issuing rescan command"); } scan(); } else { if (log.isDebugEnabled()) { log.debug("[DO UPDATE] did an update, but there is not value in root; clearing"); } tblPOMS.getItems().clear(); } tblPOMSDirty = false; tfNewVersion.setDisable(false); }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Downloads and saves locally wanted files associated with given {@link StorageData}. Files * will be saved in passed directory. The caller can specify the type of the files to download * by passing the proper {@link StorageFileType}s to the method. * // w ww. ja v a 2s . c o m * @param cmrRepositoryDefinition * {@link CmrRepositoryDefinition}. * @param storageData * {@link StorageData}. * @param directory * Directory to save objects. compressBefore Should data files be compressed on the * fly before sent. * @param compressBefore * Should data files be compressed on the fly before sent. * @param decompressContent * If the useGzipCompression is <code>true</code>, this parameter will define if the * received content will be de-compressed. If false is passed content will be saved * to file in the same format as received, but the path of the file will be altered * with additional '.gzip' extension at the end. * @param subMonitor * {@link SubMonitor} for process reporting. * @param fileTypes * Files that should be downloaded. * @throws BusinessException * If directory to save does not exists. If files wanted can not be found on the * server. * @throws IOException * If {@link IOException} occurs. */ public void downloadAndSaveStorageFiles(CmrRepositoryDefinition cmrRepositoryDefinition, StorageData storageData, final Path directory, boolean compressBefore, boolean decompressContent, SubMonitor subMonitor, StorageFileType... fileTypes) throws BusinessException, IOException { if (!Files.isDirectory(directory)) { throw new BusinessException("Download and save storage files for storage " + storageData + " to the path " + directory.toString() + ".", StorageErrorCodeEnum.FILE_DOES_NOT_EXIST); } Map<String, Long> allFiles = getFilesFromCmr(cmrRepositoryDefinition, storageData, fileTypes); if (MapUtils.isNotEmpty(allFiles)) { PostDownloadRunnable postDownloadRunnable = new PostDownloadRunnable() { @Override public void process(InputStream content, String fileName) throws IOException { String[] splittedFileName = fileName.split("/"); Path writePath = directory; // first part is empty, second is storage id, we don't need it for (int i = 2; i < splittedFileName.length; i++) { writePath = writePath.resolve(splittedFileName[i]); } // ensure all dirs are created if (Files.notExists(writePath.getParent())) { Files.createDirectories(writePath.getParent()); } Files.copy(content, writePath, StandardCopyOption.REPLACE_EXISTING); } }; this.downloadAndSaveObjects(cmrRepositoryDefinition, allFiles, postDownloadRunnable, compressBefore, decompressContent, subMonitor); } }
From source file:net.mozq.picto.core.ProcessCore.java
private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData, Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException { ProcessDataStatus status;/*from w w w . ja va 2 s .c o m*/ Path destParentPath = processData.getDestPath().getParent(); if (destParentPath != null) { Files.createDirectories(destParentPath); } if (processCondition.isCheckDigest() || (processCondition.isChangeExifDate() && processData.getBaseDate() != null) || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) { Path destTempPath = null; try { destTempPath = Files.createTempFile(processData.getDestPath().getParent(), processData.getDestPath().getFileName().toString(), null); if (processCondition.isCheckDigest()) { String algorithm = FILE_DIGEST_ALGORITHM; MessageDigest srcMD = newMessageDigest(algorithm); try (InputStream is = new DigestInputStream( new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) { Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE); } byte[] srcDigest = srcMD.digest(); MessageDigest destMD = newMessageDigest(algorithm); try (InputStream is = new DigestInputStream( new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) { byte[] b = new byte[1024]; while (is.read(b) != -1) { } } byte[] destDigest = destMD.digest(); if (!isSame(srcDigest, destDigest)) { throw new PictoFileDigestMismatchException( Messages.getString("message.error.digest.mismatch")); } } else if (processCondition.isRemveExifTagsAll()) { ExifRewriter exifRewriter = new ExifRewriter(); try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) { exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os); } catch (ImageReadException | ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) { ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath()); TiffOutputSet outputSet = getOutputSet(imageMetadata); if (outputSet == null) { Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE); } else { if (processCondition.isChangeExifDate()) { SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN); exifDateFormat.setTimeZone(processCondition.getTimeZone()); String exifBaseDate = exifDateFormat.format(processData.getBaseDate()); DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN); String exifBaseSubsec = exifSubsecFormat .format((int) (processData.getBaseDate().getTime() / 10) % 100); try { TiffOutputDirectory rootDirectory = outputSet.getRootDirectory(); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (rootDirectory != null) { rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME); rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate); } if (exifDirectory != null) { exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL); exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL, exifBaseSubsec); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED); exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate); exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED); exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED, exifBaseSubsec); } } catch (ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } if (processCondition.isRemveExifTagsGps()) { outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO); } ExifRewriter exifRewriter = new ExifRewriter(); try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) { exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os, outputSet); } catch (ImageReadException | ImageWriteException e) { throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e); } } } Path destPath; if (processCondition.getOperationType() == OperationType.Overwrite) { destPath = processData.getSrcPath(); } else { destPath = processData.getDestPath(); } try { Files.move(destTempPath, destPath, OPTIONS_MOVE); if (processCondition.getOperationType() == OperationType.Move) { Files.deleteIfExists(processData.getSrcPath()); } status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { // Overwrite Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE); if (processCondition.getOperationType() == OperationType.Move) { Files.deleteIfExists(processData.getSrcPath()); } status = ProcessDataStatus.Success; } } } finally { if (destTempPath != null) { Files.deleteIfExists(destTempPath); } } } else { switch (processCondition.getOperationType()) { case Copy: try { Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY); status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE); status = ProcessDataStatus.Success; } } break; case Move: try { Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE); status = ProcessDataStatus.Success; } catch (FileAlreadyExistsException e) { status = confirmOverwrite(processCondition, processData, overwriteConfirm); if (status == ProcessDataStatus.Processing) { Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE); status = ProcessDataStatus.Success; } } break; case Overwrite: // NOP status = ProcessDataStatus.Success; break; default: throw new IllegalStateException(processCondition.getOperationType().toString()); } } if (status == ProcessDataStatus.Success) { FileTime creationFileTime = processData.getSrcFileAttributes().creationTime(); FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime(); FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime(); if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate() || processCondition.isChangeFileAccessDate()) { if (processData.getBaseDate() != null) { FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime()); if (processCondition.isChangeFileCreationDate()) { creationFileTime = baseFileTime; } if (processCondition.isChangeFileModifiedDate()) { modifiedFileTime = baseFileTime; } if (processCondition.isChangeFileAccessDate()) { accessFileTime = baseFileTime; } } } BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(), BasicFileAttributeView.class); attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime); } return status; }
From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java
private void copy(final Context context, final String... fragments) throws IOException { Files.copy(toInput(String.join("/", fragments)), utils.toFile(context.getSubscription(), fragments).toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:com.cloudbees.clickstack.util.Files2.java
/** * Copy content for {@code srcDir} to {@code destDir} * * @param srcDir//from w ww. j a va 2 s.com * @param destDir * @throws RuntimeIOException */ public static void copyDirectoryContent(@Nonnull final Path srcDir, @Nonnull final Path destDir) throws RuntimeIOException { logger.trace("Copy from {} to {}", srcDir, destDir); FileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetPath = destDir.resolve(srcDir.relativize(dir)); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, destDir.resolve(srcDir.relativize(file)), StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(srcDir, copyDirVisitor); } catch (IOException e) { throw new RuntimeIOException("Exception copying content of dir " + srcDir + " to " + destDir, e); } }
From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java
private void copyFromTo(final Context context, final String from, final String... toFragments) throws IOException { Files.copy(toInput(from), utils.toFile(context.getSubscription(), toFragments).toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** * Check for new versions of VirtMus./* w w w .j a va 2s . c o m*/ * @param installId The random ID identifying this install. * @param prevVersion The previous version of VirtMus installed. * @param statsEnabled Set to true if the user is participating in stats collection. */ private static void checkForNewVersion(long installId, String prevVersion, UploadStats statsEnabled) { final String urlStr = pref.get(Options.OptCheckVersionUrl, CHECK_VERSION); // Catch redirects. HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() { @Override public void handlePermanentRedirect(HttpRequest request, HttpResponse response, HttpUriRequest redirect) { if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(urlStr)) { pref.put(Options.OptCheckVersionUrl, newUrl); } } }; // TODO: Use http://wiki.fasterxml.com/JacksonHome to avoid warnings? String postData = new JSONStringer().object().key("version").value(MainApp.VERSION) /* installId MUST be sent as string since JS on the server side only has 64-bit float values and can't represent all long int values, leading to truncation of some digits since the JS float mantisa has only 53 bits (not 64). See: http://www.2ality.com/2012/07/large-integers.html */ .key("installId").value(String.valueOf(installId)).key("prevVersion").value(prevVersion) .key("statsEnabled").value(statsEnabled.name()).endObject().toString(); try { CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build(); HttpPost post = new HttpPost(urlStr); addHttpHeaders(post); StringEntity entity = new StringEntity(postData, ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { // 200 if (statsEnabled == UploadStats.No) { // If the user doesn't want to participate, he probably doesn't // want to be checking for new releases either, so disable it. pref.putBoolean(Options.OptCheckVersion, false); } // This is used to notify the user that a newer version is available HttpEntity rspEntity = response.getEntity(); if (rspEntity != null && statsEnabled != UploadStats.No) { File f = File.createTempFile("VersionPost", "html"); f.deleteOnExit(); Files.copy(rspEntity.getContent(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); if (f.length() > 0) { URL rspUrl = Utilities.toURI(f).toURL(); HtmlBrowser.URLDisplayer.getDefault().showURL(rspUrl); } } } else { Log.log(Level.INFO, "CheckVersion result: {0}", status); } } catch (MalformedURLException ex) { Log.log(ex); } catch (IOException ex) { Log.log(ex); } }
From source file:com.warfrog.bitmapallthethings.BattEngine.java
private void decodeBitmap(String filename) throws IOException { System.out.println("Decoding " + filename); File inputFile = new File(filename); File outputFile = new File( outputDirectory + File.separator + FilenameUtils.removeExtension(inputFile.getName())); FileInputStream fis = new FileInputStream(filename); //skip 6 bytes fis.skip(6);//from w ww. j a v a2 s.com //read the length we encoded int fileSize = EndianUtils.readSwappedInteger(fis); //skip the rest of the header fis.skip(44); Files.copy(fis, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); //truncate the file FileChannel outChan = new FileOutputStream(outputFile, true).getChannel(); outChan.truncate(fileSize); outChan.close(); //clean up if (isCleanUp()) { //delete the bitmap System.out.println("Deleting: " + inputFile); FileUtils.deleteQuietly(inputFile); } }
From source file:model.settings.ReadSettings.java
/** * Set up paint as program in OSX.//from w w w . jav a 2 s . com */ private static void installLinux() { /* * setting up "open with" links for paint. * Therefore request SUDO rights. */ try { final String userHome = System.getProperty("user.home"); final String localDest = userHome + "/paint.desktop"; final String finalDest = "/usr/share/applications/paint.desktop"; Util.exportResource("/res/files/paint.desktop", localDest); String passwd = ""; /* * Check whether the execution was successfully (and the password * was correct) or the file already exists */ while (!new File(finalDest).exists()) { /* * Request SUDO privileges. */ passwd = Util.requestSudoRights("mv " + localDest + " " + finalDest); if (passwd.equals("")) { JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges."); return; } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } /* * Copy jar file */ /////////////////////////Path for jar file./////////////////// // /usr/lib/paint/paint.jar requests sudo rights. // because of this, each time an update is done these rights // have to be requested. Thus chose another path: // ~/.PaintUni/paint.jar // (PROGRAM_LOCATION/paint.jar) /* * STEP 2: Create (executable) file which is called if the * application is run. */ final String dest_jar_file = PROGRAM_LOCATION + "paint.jar"; final String dest_exec = "/usr/bin/paint"; String orig_jar_file = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8"); // if Eclipse on-the-fly-compiling final String eclipseSubstring = "target/classes/"; if (orig_jar_file.endsWith(eclipseSubstring)) { orig_jar_file = orig_jar_file.substring(0, orig_jar_file.length() - eclipseSubstring.length()); } orig_jar_file += "paint.jar"; /* * Step 3: Copy .jar file to the destination. */ try { Files.copy(Paths.get(orig_jar_file), Paths.get(dest_jar_file), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { final String command1 = "cp " + "\"" + orig_jar_file + "\"" + " " + "\"" + dest_jar_file + "\""; String ret1 = Util.executeCommandLinux(command1); System.out.println(command1 + "" + ret1); } final String content = "#!/bin/bash \n" + "java -jar " + dest_jar_file + " $1"; // rather dirty solution. Creating a temporary file which is copied // to another location which requests sudoer rights. // If the temporary file already exists, randomly change the name. String temporaryLocation = userHome + "/paint_tmp_0123"; while (new File(temporaryLocation).exists()) { temporaryLocation += "" + new Random().nextInt(10); } PrintWriter writer = new PrintWriter(temporaryLocation, "UTF-8"); writer.println(content); writer.close(); final String command = "mv " + temporaryLocation + " " + dest_exec; Util.execSudoCommand(command, passwd); // if the password was not correct / no sudo rights if (!new File(dest_exec).exists()) { while (!new File(dest_exec).exists()) { /* * Request SUDO privileges. */ passwd = Util.requestSudoRights(command); if (passwd.equals("")) { JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges."); return; } try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Util.execSudoCommand("chmod a+x " + dest_exec, passwd); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }