Example usage for java.nio.file Path getFileName

List of usage examples for java.nio.file Path getFileName

Introduction

In this page you can find the example usage for java.nio.file Path getFileName.

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:misc.FileHandler.java

/**
 * Returns a temporary file path that is on the same file store as the given
 * file. The temporary file is created without content, if the given file's
 * file store is identical to the system's default temporary directory file
 * store.//from  www.j  a  v a 2  s.com
 * 
 * @param target
 *            the file which determines the file store.
 * @return the path of the temporary file or <code>null</code>, if an error
 *         occurred.
 */
public static Path getTempFile(Path target) {
    Path tempFile = null;
    boolean success = false;

    target = target.normalize();

    try {
        Path targetDirectory = target.toAbsolutePath().getParent();
        tempFile = Files.createTempFile(target.getFileName().toString(), TEMP_FILE_SUFFIX);

        if (!Files.getFileStore(tempFile).equals(Files.getFileStore(targetDirectory))) {
            // the temporary file should be in the target directory.
            Files.delete(tempFile);
            tempFile = Paths.get(targetDirectory.toString(), tempFile.getFileName().toString());
            success = true;
        } else {
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (!success && (tempFile != null)) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException innerE) {
                Logger.logError(innerE);
            }
        }
    }

    return success ? tempFile : null;
}

From source file:com.googlecode.jmxtrans.model.output.FileWriter.java

public FileWriter(@JsonProperty("typeNames") ImmutableList<String> typeNames,
        @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled,
        @JsonProperty(PROPERTY_BASEPATH) String filepath, @JsonProperty(PROPERTY_LINE_FORMAT) String lineFormat,
        @JsonProperty("settings") Map<String, Object> settings) throws IOException {
    super(typeNames, booleanAsNumber, debugEnabled, settings);

    this.outputFile = new File(filepath);
    Path outputFilePath = outputFile.toPath();
    this.outputTempFile = new File(
            outputFilePath.getParent() + File.separator + "." + outputFilePath.getFileName());
    if (lineFormat == null) {
        this.lineFormat = DEFAULT_LINE_FORMAT;
    } else {/*from   w  ww.  ja va  2s.c  om*/
        this.lineFormat = lineFormat;
    }

    // make sure the permissions allow to manage these files:
    touch(this.outputFile);
    touch(this.outputTempFile);
}

From source file:org.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java

private void clearLogs(final Path path) throws IOException {
    final String expectedName = path.getFileName().toString();
    Files.walkFileTree(path.getParent(), new SimpleFileVisitor<Path>() {
        @Override/*from   ww  w  .j a  va  2  s  .  co m*/
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String currentName = file.getFileName().toString();
            if (currentName.startsWith(expectedName)) {
                Files.delete(file);
            }
            return super.visitFile(file, attrs);
        }
    });
}

From source file:com.google.cloud.tools.managedcloudsdk.install.TarGzExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(Files.newInputStream(archive));
    try (TarArchiveInputStream in = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;//from   w w  w.j a va 2 s  . c  o m
        while ((entry = in.getNextTarEntry()) != null) {
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else if (entry.isFile()) {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    IOUtils.copy(in, out);
                    PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                            PosixFileAttributeView.class);
                    if (attributeView != null) {
                        attributeView.setPermissions(PosixUtil.getPosixFilePermissions(entry.getMode()));
                    }
                }
            } else {
                // we don't know what kind of entry this is (we only process directories and files).
                logger.warning("Skipping entry (unknown type): " + entry.getName());
            }
        }
        progressListener.done();
    }
}

From source file:neembuu.uploader.v2tov3conversion.ConvertUploaderClass.java

public ConvertUploaderClass(Path in) throws IOException {
    String myClassName = in.getFileName().toString();
    myClassName = myClassName.substring(0, myClassName.indexOf("."));
    this.myClassName = myClassName;
    is = Files.readAllLines(in, Charset.defaultCharset());
}

From source file:org.sakuli.services.forwarder.ScreenshotDivConverter.java

protected String extractScreenshotFormat(Throwable exception) {
    if (exception instanceof SakuliExceptionWithScreenshot) {
        Path screenshotPath = ((SakuliExceptionWithScreenshot) exception).getScreenshot();
        if (screenshotPath != null) {
            return StringUtils.substringAfterLast(screenshotPath.getFileName().toString(), ".");
        }//w  ww  . ja  v  a2  s . c  o m
    }
    return null;
}

From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
    // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
    // all the zip file data and will return "0" for any call to getUnixMode().
    try (ZipFile zipFile = new ZipFile(archive.toFile())) {
        // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }//  w  w  w .j  a v a  2 s .  c  om

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        IOUtils.copy(in, out);
                        PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                                PosixFileAttributeView.class);
                        if (attributeView != null) {
                            attributeView
                                    .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
                        }
                    }
                }
            }
        }
    }
    progressListener.done();
}

From source file:im.bci.gamesitekit.GameSiteKitMain.java

private List<ScreenshotMV> createScreenshotsMV(Path localeOutputDir) throws IOException {
    List<ScreenshotMV> screenshots = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(screenshotThumbnailsOutputDir, IMAGE_GLOB)) {
        for (Path thumbnail : stream) {
            Path screenshot = screenshotsOutputDir.resolve(thumbnail.getFileName());
            if (Files.exists(screenshot)) {
                ScreenshotMV mv = new ScreenshotMV();
                mv.setFull(localeOutputDir.relativize(screenshot).toString().replace('\\', '/'));
                mv.setThumbnail(localeOutputDir.relativize(thumbnail).toString().replace('\\', '/'));
                screenshots.add(mv);/*from   w w w.  ja  v a2  s.co  m*/
            }
        }
    }
    Collections.sort(screenshots, new Comparator<ScreenshotMV>() {

        @Override
        public int compare(ScreenshotMV o1, ScreenshotMV o2) {
            return o1.getFull().compareTo(o2.getFull());
        }

    });
    return screenshots;
}

From source file:at.ac.tuwien.infosys.repository.LocalComponentRepository.java

protected List<Resource> createResources(List<Path> resources) {
    List<Resource> result = new ArrayList<Resource>();

    for (Path path : resources) {
        Resource resource = new Resource();
        resource.setName(path.getFileName().toString());
        try {//from  www  . j a  v  a2s. c om
            resource.setUri(path.toUri().toURL());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        result.add(resource);
    }
    return result;
}

From source file:com.yqboots.fss.core.support.FileTypeFilterPredicate.java

/**
 * {@inheritDoc}//from   w w w .j a  va  2 s  .  co  m
 */
@Override
public boolean test(final Path path) {
    if (!Files.isRegularFile(path)) {
        return false;
    }

    boolean result = false;
    for (final String fileType : acceptedFileTypes) {
        if (StringUtils.endsWith(path.getFileName().toString(), fileType)) {
            result = true;
            break;
        }
    }

    return result;
}