List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java
/** * ?????./*from www.ja v a 2s.c om*/ * * @param metadata ?urlTree * @param ctx urlTree */ @Override public void save(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx) throws BadContentException { String localFileName = metadata.getAbsolutePath(); logger.debug("saving " + localFileName); Path f = this.generateFileObj(localFileName); InputStream b = metadata.getData(); // null????????? if (b == null) { return; } try { Path parent = f.getParent(); // ??????? if (Files.notExists(parent)) { Files.createDirectories(parent); } Files.copy(b, f, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new GenericResourceException(e); } }
From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java
private void remoteCopy(Path source, Path target, CopyOption... options) throws IOException { Configuration configuration = getConfiguration(); Path tmp = target.getParent(); Path dest = null;/*from ww w .j a v a2 s . c o m*/ do { dest = tmp.resolve(String.format("tmp%s/", System.currentTimeMillis())); } while (Files.exists(dest)); try { DistCpOptions distCpOptions = new DistCpOptions( Arrays.asList(((HadoopFileSystemPath) source).getPath()), ((HadoopFileSystemPath) dest).getPath()); List<CopyOption> optionList = Arrays.asList(options); distCpOptions.setOverwrite(optionList.contains(StandardCopyOption.REPLACE_EXISTING)); try { DistCp distCp = new DistCp(configuration, distCpOptions); Job job = distCp.execute(); job.waitForCompletion(true); } catch (Exception e) { throw new IOException(e.getLocalizedMessage(), e); } move(dest.resolve(source.getFileName()), target, options); } finally { delete(dest, false); } }
From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java
/** * 2 newLines are needed at the end of file for file to be included without protection. *//* ww w.ja v a 2 s . c o m*/ @Override public void writeToFileWithoutExtension(Path file, Charset charset, OpenOption... options) { try { Files.createDirectories(file.getParent()); } catch (IOException e) { throw new RuntimeException("Failed create directory", e); } try (BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) { writer.write(toString()); writer.write(newLine); writer.write(newLine); } catch (IOException e) { throw new RuntimeException("Failed to write file", e); } if (logger.isInfoEnabled()) { logger.info("Markup document written to: {}", file); } }
From source file:org.esa.s2tbx.dataio.s2.Sentinel2ProductReader.java
/** * From a granule path, search a jpeg file for the given resolution, extract tile layout * information and update/*from w w w . j a v a 2 s . c o m*/ * * @param granuleMetadataFilePath the complete path to the granule metadata file * @param resolution the resolution for which we wan to find the tile layout * @return the tile layout for the resolution, or {@code null} if none was found */ public TileLayout retrieveTileLayoutFromGranuleMetadataFile(Path granuleMetadataFilePath, S2SpatialResolution resolution) { TileLayout tileLayoutForResolution = null; if (Files.exists(granuleMetadataFilePath) && granuleMetadataFilePath.toString().endsWith(".xml")) { Path granuleDirPath = granuleMetadataFilePath.getParent(); tileLayoutForResolution = retrieveTileLayoutFromGranuleDirectory(granuleDirPath, resolution); } return tileLayoutForResolution; }
From source file:org.esa.s2tbx.dataio.s2.Sentinel2ProductReader.java
/** * From a product path, search a jpeg file for the given resolution, extract tile layout * information and update/* w w w . ja v a2s .c om*/ * * @param productMetadataFilePath the complete path to the product metadata file * @param resolution the resolution for which we wan to find the tile layout * @return the tile layout for the resolution, or {@code null} if none was found */ public TileLayout retrieveTileLayoutFromProduct(Path productMetadataFilePath, S2SpatialResolution resolution) { TileLayout tileLayoutForResolution = null; if (Files.exists(productMetadataFilePath) && productMetadataFilePath.toString().endsWith(".xml")) { Path productFolder = productMetadataFilePath.getParent(); Path granulesFolder = productFolder.resolve("GRANULE"); try { DirectoryStream<Path> granulesFolderStream = Files.newDirectoryStream(granulesFolder); for (Path granulePath : granulesFolderStream) { tileLayoutForResolution = retrieveTileLayoutFromGranuleDirectory(granulePath, resolution); if (tileLayoutForResolution != null) { break; } } } catch (IOException e) { SystemUtils.LOG.warning("Could not retrieve tile layout for product " + productMetadataFilePath.toAbsolutePath().toString() + " error returned: " + e.getMessage()); } } return tileLayoutForResolution; }
From source file:org.roda_project.commons_ip.model.impl.eark.EARKAIP.java
private void writeFileToPath(final ZipEntryInfo zipEntryInfo, final Path outputPath, final boolean onlyMets) throws IOException, NoSuchAlgorithmException { InputStream is = null;/*from ww w . j a v a 2 s . c o m*/ OutputStream os = null; try { is = Files.newInputStream(zipEntryInfo.getFilePath()); if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) { Files.createDirectories(outputPath.getParent()); os = Files.newOutputStream(outputPath); } else { os = new NullOutputStream(); } final byte[] buffer = new byte[4096]; final MessageDigest complete = MessageDigest.getInstance(IPConstants.CHECKSUM_ALGORITHM); int numRead; do { numRead = is.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) { os.write(buffer, 0, numRead); } } } while (numRead != -1); setChecksum(zipEntryInfo, DatatypeConverter.printHexBinary(complete.digest()), IPConstants.CHECKSUM_ALGORITHM); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
From source file:company.gonapps.loghut.dao.PostDao.java
public void delete(PostDto post) throws IOException { Path postPath = Paths.get(getPostPathString(post)); rrwl.writeLock().lock();/*from w w w. j a va2s. c o m*/ try { Files.delete(postPath); FileUtils.rmdir(postPath.getParent(), new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path path) throws IOException { return !postPathStringPattern.matcher(path.toString()).find(); } }); FileUtils.rmdir(postPath.getParent().getParent(), new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path path) throws IOException { return (!postMonthPattern.matcher(path.toString()).find()) || (!Files.isDirectory(path)); } }); } finally { rrwl.writeLock().unlock(); } }
From source file:io.uploader.drive.drive.DriveOperations.java
private static void uploadFiles(OperationResult operationResult, Map<Path, File> localPathDriveFileMapping, Drive client, Path srcDir, boolean overwrite, final StopRequester stopRequester, final HasStatusReporter statusReporter) throws IOException { Queue<Path> filesQueue = io.uploader.drive.util.FileUtils.getAllFilesPath(srcDir, FileFinderOption.FILE_ONLY); int count = 0; for (Path path : filesQueue) { try {//from ww w . j a v a 2 s . co m if (statusReporter != null) { BasicFileAttributes attr = io.uploader.drive.util.FileUtils.getFileAttr(path); StringBuilder sb = new StringBuilder(); sb.append("Transfering files ("); sb.append(path.getFileName().toString()); if (attr != null) { sb.append(" - size: "); sb.append(io.uploader.drive.util.FileUtils.humanReadableByteCount(attr.size(), true)); } sb.append(")"); statusReporter.setStatus(sb.toString()); } if (hasStopBeenRequested(stopRequester)) { if (statusReporter != null) { statusReporter.setStatus("Stopped!"); } operationResult.setStatus(OperationCompletionStatus.STOPPED); return; } final File driveParent = localPathDriveFileMapping.get(path.getParent()); if (driveParent == null) { throw new IllegalStateException( "The path " + path.toString() + " does not have any parent in the drive (parent path " + path.getParent().toString() + ")..."); } InputStreamProgressFilter.StreamProgressCallback progressCallback = null; if (statusReporter != null) { progressCallback = new InputStreamProgressFilter.StreamProgressCallback() { @Override public void onStreamProgress(double progress) { if (statusReporter != null) { statusReporter.setCurrentProgress(progress); } } }; } uploadFile(operationResult, client, driveParent, path, overwrite, progressCallback); ++count; if (statusReporter != null) { double p = ((double) count) / filesQueue.size(); statusReporter.setTotalProgress(p); statusReporter.setStatus("Transfering files..."); } } catch (Throwable e) { logger.error("Error occurred while transfering the file " + path.toString(), e); operationResult.setStatus(OperationCompletionStatus.ERROR); operationResult.addError(path, e); } } }
From source file:business.services.FileService.java
public HttpEntity<InputStreamResource> downloadAccessLog(String filename, boolean writeContentDispositionHeader) { try {//from w w w. ja v a 2s .co m FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath(accessLogsPath).normalize(); filename = filename.replace(fileSystem.getSeparator(), "_"); filename = URLEncoder.encode(filename, "utf-8"); Path f = fileSystem.getPath(accessLogsPath, filename).normalize(); // filter path names that point to places outside the logs path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, f.getParent())) { // Path f is not in the upload path. Maybe 'name' contains '..'? log.error("Invalid filename: " + filename); throw new FileDownloadError("Invalid file name"); } if (!Files.isReadable(f)) { log.error("File does not exist: " + filename); throw new FileDownloadError("File does not exist"); } InputStream input = new FileInputStream(f.toFile()); InputStreamResource resource = new InputStreamResource(input); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); if (writeContentDispositionHeader) { headers.set("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_")); } HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers); return response; } catch (IOException e) { log.error(e); throw new FileDownloadError(); } }
From source file:com.willwinder.universalgcodesender.utils.Settings.java
public void setLastOpenedFilename(String absolutePath) { Path p = Paths.get(absolutePath).toAbsolutePath(); this.fileName = p.toString(); updateRecentFiles(p.toString());//ww w .ja va 2s .c om updateRecentDirectory(p.getParent().toString()); changed(); }