Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:pinterestbackup.PINDownloader.java

/**
 * This method retrieve a pin connecting via HTTP to URLSource and copy the content
 * to the specified pathSave.// ww  w. ja  va 2  s .com
 * 
 * @param pin
 * @param pinPath: Path to save
 * @throws pinterestbackup.exceptions.PinCopyException
 */
public void savePinToFile(PinterestPin pin, Path pinPath) throws PinCopyException {
    HttpGet httpgetImg = new HttpGet();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    if (pinPath == null)
        return;

    //Check if file exists
    if (this.localFiles.containsKey(pinPath.toString())) {
        //if (Files.exists(pinPath)){
        logPIN.log(Level.INFO, "Board {0} PIN {1} already exists.",
                new Object[] { board.getName(), pin.getUrl() });
        return;
    }

    logPIN.log(Level.INFO, "Save Board {0} PIN {1} to path.", new Object[] { board.getName(), pin.getUrl() });

    try {
        URI uri = new URI(pin.getUrl());
        httpgetImg.setURI(uri);
        CloseableHttpResponse response = httpclient.execute(httpgetImg);
        try (InputStream instream = response.getEntity().getContent()) {
            Files.copy(instream, pinPath);
        }
    } catch (IOException | URISyntaxException ex) {
        throw new PinCopyException(ex.getMessage());
    }
}

From source file:com.pawandubey.griffin.model.Post.java

/**
 * Creates a Post with the given paramenter.
 *  @param title the post title//from w w w. j av a  2  s . c  o m
 * @param auth the post author
 * @param dat the post date
 * @param loc the post's Path
 * @param cont the post's content
 * @param image
 * @param slu the post slug
 * @param lay the layout
 * @param tag the list of tags
 */
public Post(String title, String auth, LocalDate dat, Path loc, String cont, String image, String slu,
        String lay, List<String> tag) {
    this.title = title;
    author = auth;
    date = dat;
    prettyDate = date.format(DateTimeFormatter.ofPattern(config.getOutputDateFormat()));
    location = loc.toString();
    setContent(cont);
    slug = slu;
    layout = lay;
    tags = tag;
    featuredImage = image;
}

From source file:com.spectralogic.ds3cli.command.PutBulk.java

private Iterable<Path> getFilesToPut() throws IOException {
    final Iterable<Path> filesToPut;
    if (this.pipe) {
        filesToPut = this.pipedFiles;
    } else {//w ww . j  a  v a 2 s  .co m
        filesToPut = FileUtils.listObjectsForDirectory(this.inputDirectory);
    }
    return new FilteringIterable<>(filesToPut, new FilteringIterable.FilterFunction<Path>() {
        @Override
        public boolean filter(final Path item) {
            final boolean filter = !(followSymlinks || !Files.isSymbolicLink(item));
            if (filter) {
                LOG.info("Skipping: {}", item.toString());
            }
            return filter;
        }
    });
}

From source file:androidassetsgenerator.AssetGenerator.java

private File path(String fileName, String outputDir, String outputSize) {
    String name = FilenameUtils.removeExtension(fileName);
    String extension = FilenameUtils.getExtension(fileName);
    Path path = Paths.get(
            outputDir + Constants.SLASH + Constants.PREFIX + name.toUpperCase() + Constants.SLASH + outputSize);

    if (!Files.exists(path)) {
        try {//from w w w  .ja  va  2 s .  c  om
            Files.createDirectories(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    File file = new File(path.toString() + Constants.SLASH + Constants.PREFIX + name.toUpperCase()
            + Constants.DOT + extension);

    return file;
}

From source file:jonelo.jacksum.concurrent.Jacksum2Cli.java

private void buildFilesReport(JacksumReport report, HashFormat simpleFormat)
        throws IOException, NoSuchAlgorithmException, InterruptedException, ExecutionException {
    final List<Path> allFiles = new ArrayList<>();
    final Map<Path, Long> fileSizes = new ConcurrentHashMap<>();
    final Map<Path, Long> fileLastModified = new ConcurrentHashMap<>();
    this.loadFilesToHash(allFiles, fileSizes, fileLastModified);
    final Map<Pair<Path, Algorithm>, byte[]> results = new ConcurrentHasher().hashFiles(allFiles,
            this.algorithms, this.alternative, GENERIC_CRC_SPECS);

    for (Path fn : allFiles) {
        report.addLine(fn.toString(),
                simpleFormat.format(algorithms, this.algorithms.stream()
                        .map(algo -> results.get(new Pair<>(fn, algo))).collect(Collectors.toList())),
                fileSizes.get(fn));//from w  w w  . jav a 2 s  .  c o  m

    }
}

From source file:audiomanagershell.commands.FavCommand.java

@Override
public void execute() throws CommandException {
    Path file = Paths.get(this.pathRef.toString(), this.arg);

    if (!Files.exists(file))
        throw new FileNotFoundException(file.getFileName().toString());
    if (!Files.isRegularFile(file))
        throw new NotAFileException(file.getFileName().toString());

    List<String> validExtensions = Arrays.asList("wav", "mp3", "flac", "mp4");
    if (!validExtensions.contains(FilenameUtils.getExtension(file.toString())))
        throw new NotAudioFileException(file.toString());

    try (PrintWriter output = new PrintWriter(new FileWriter(favFile.toFile(), true));
            Scanner input = new Scanner(new FileReader(favFile.toString()))) {

        while (input.hasNextLine()) {
            if (input.nextLine().equals(file.toString())) {
                System.out.printf("File \"%s\" is already added to favorite List!%n", file);
                return;
            }/*  w  w w.jav  a  2s .c o  m*/
        }
        System.out.printf("Added: \"%s\"%n", file);
        output.println(file);
    } catch (IOException ex) {
        throw new CommandException("Error related from I/O to file:" + favFile.toString());
    }
}

From source file:com.spectralogic.ds3client.metadata.MetadataReceivedListenerImpl_Test.java

@Test
public void testGettingMetadataFailureHandler() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    try {/*from ww  w  .ja  v a2 s . c  o m*/
        final String tempPathPrefix = null;
        final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

        final String fileName = "Gracie.txt";

        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        try {
            // set permissions
            if (!Platform.isWindows()) {
                final PosixFileAttributes attributes = Files.readAttributes(filePath,
                        PosixFileAttributes.class);
                final Set<PosixFilePermission> permissions = attributes.permissions();
                permissions.clear();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                Files.setPosixFilePermissions(filePath, permissions);
            }

            // get permissions
            final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
            fileMapper.put(filePath.toString(), filePath);
            final Map<String, String> metadataFromFile = new MetadataAccessImpl(fileMapper.build())
                    .getMetadataValue(filePath.toString());

            FileUtils.deleteDirectory(tempDirectory.toFile());

            // put old permissions back
            final Metadata metadata = new MetadataImpl(new MockedHeadersReturningKeys(metadataFromFile));

            final AtomicInteger numTimesFailureHandlerCalled = new AtomicInteger(0);

            new MetadataReceivedListenerImpl(tempDirectory.toString(), new FailureEventListener() {
                @Override
                public void onFailure(final FailureEvent failureEvent) {
                    numTimesFailureHandlerCalled.incrementAndGet();
                    assertEquals(FailureEvent.FailureActivity.RestoringMetadata, failureEvent.doingWhat());
                }
            }, "localhost").metadataReceived(fileName, metadata);

            assertEquals(1, numTimesFailureHandlerCalled.get());
        } finally {
            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    } catch (final Throwable t) {
        fail("Throwing exceptions from metadata est verbotten");
    }
}

From source file:com.github.cbismuth.fdupes.collect.PathAnalyser.java

private Path onMatch(final Path destination, final Matcher matcher) {
    final String year = matcher.group(1);
    final String month = matcher.group(2);
    final String day = matcher.group(3);
    final String hour = matcher.group(4);
    final String minute = matcher.group(5);
    final String second = matcher.group(6);
    final String extension = matcher.group(7);

    Path newPath = Paths.get(destination.toString(), year, month,
            new StringBuilder().append(year).append(month).append(day).append(hour).append(minute)
                    .append(second).append('.').append(extension).toString().toUpperCase(getDefault()));

    int i = 1;//from   www.  ja v a 2s  .c  o  m
    while (Files.exists(newPath)) {
        newPath = Paths.get(destination.toString(), year, month,
                new StringBuilder().append(year).append(month).append(day).append(hour).append(minute)
                        .append(second).append('-').append(i++).append('.').append(extension).toString()
                        .toUpperCase(getDefault()));
    }

    return newPath;
}

From source file:com.spectralogic.ds3client.metadata.MetadataReceivedListenerImpl_Test.java

@Test
public void testGettingMetadata() throws IOException, InterruptedException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

    try {// w w w. j  ava  2  s . co m
        // set permissions
        if (!Platform.isWindows()) {
            final PosixFileAttributes attributes = Files.readAttributes(filePath, PosixFileAttributes.class);
            final Set<PosixFilePermission> permissions = attributes.permissions();
            permissions.clear();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            Files.setPosixFilePermissions(filePath, permissions);
        }

        // get permissions
        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
        fileMapper.put(filePath.toString(), filePath);
        final ImmutableMap<String, Path> immutableFileMapper = fileMapper.build();
        final Map<String, String> metadataFromFile = new MetadataAccessImpl(immutableFileMapper)
                .getMetadataValue(filePath.toString());

        // change permissions
        if (Platform.isWindows()) {
            Runtime.getRuntime().exec("attrib -A " + filePath.toString()).waitFor();
        } else {
            final PosixFileAttributes attributes = Files.readAttributes(filePath, PosixFileAttributes.class);
            final Set<PosixFilePermission> permissions = attributes.permissions();
            permissions.clear();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            permissions.add(PosixFilePermission.OWNER_EXECUTE);
            Files.setPosixFilePermissions(filePath, permissions);
        }

        // put old permissions back
        final Metadata metadata = new MetadataImpl(new MockedHeadersReturningKeys(metadataFromFile));

        new MetadataReceivedListenerImpl(tempDirectory.toString()).metadataReceived(fileName, metadata);

        // see that we put back the original metadata
        fileMapper.put(filePath.toString(), filePath);
        final Map<String, String> metadataFromUpdatedFile = new MetadataAccessImpl(immutableFileMapper)
                .getMetadataValue(filePath.toString());

        if (Platform.isWindows()) {
            assertEquals("A", metadataFromUpdatedFile
                    .get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_FLAGS));
        } else {
            assertEquals("100600", metadataFromUpdatedFile
                    .get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_MODE));
            assertEquals("600(rw-------)", metadataFromUpdatedFile
                    .get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_PERMISSION));
        }

    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:com.facebook.buck.util.ProjectFilesystemTest.java

@Test
public void testDeleteFileAtPath() throws IOException {
    Path path = Paths.get("foo.txt");
    File file = tmp.newFile(path.toString());
    assertTrue(file.exists());//from   ww w  . ja va 2s  .  co m
    filesystem.deleteFileAtPath(path);
    assertFalse(file.exists());
}