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:com.nsn.squirrel.tab.utils.PathUtils.java

/**
 * Root path have no file name./* w w  w .ja v a  2 s .  c  om*/
 * 
 * @param path
 * @return file name
 */
public static String getFileName(Path path) {

    String pathString = null;
    if (path != null) {
        if (path.getFileName() != null) {
            pathString = path.getFileName().toString();
        } else {
            pathString = path.toString();
        }
    }
    return pathString;
}

From source file:org.transitime.gtfs.GtfsUpdatedModule.java

/**
 * Copies the specified file to a directory at the same directory level but
 * with the directory name that is the last modified date of the file (e.g.
 * 03-28-2015)./*  w ww .j  a  v  a 2  s .c  om*/
 * 
 * @param fullFileName
 *            The full name of the file to be copied
 */
private static void archive(String fullFileName) {
    // Determine name of directory to archive file into. Use date of
    // lastModified time of file e.g. MM-dd-yyyy.
    File file = new File(fullFileName);
    Date lastModified = new Date(file.lastModified());
    String dirName = Time.dateStr(lastModified);

    // Copy the file to the sibling directory with the name that is the
    // last modified date (e.g. 03-28-2015)
    Path source = Paths.get(fullFileName);
    Path target = source.getParent().getParent().resolve(dirName).resolve(source.getFileName());

    logger.info("Archiving file {} to {}", source.toString(), target.toString());

    try {
        // Create the directory where file is to go
        String fullDirName = target.getParent().toString();
        new File(fullDirName).mkdir();

        // Copy the file to the directory
        Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
    } catch (IOException e) {
        logger.error("Was not able to archive GTFS file {} to {}", source.toString(), target);
    }
}

From source file:de.monticore.io.paths.IterablePath.java

/**
 * Creates a new {@link IterablePath} based on the supplied set of {@link Path}s containing all
 * files with the specified extensions. Note: an empty set of extensions will yield an empty
 * {@link IterablePath}.//from  w w  w  . j  a v a 2s .  com
 * 
 * @param paths
 * @param extensions
 * @return
 */
public static IterablePath fromPaths(List<Path> paths, Set<String> extensions) {
    Map<Path, Path> pMap = new LinkedHashMap<>();
    for (Path path : paths) {
        List<Path> entries = walkFileTree(path).filter(getExtensionsPredicate(extensions))
                .collect(Collectors.toList());
        for (Path entry : entries) {
            Path key = path.relativize(entry);
            if (key.toString().isEmpty()) {
                key = entry;
            }
            if (pMap.get(key) != null) {
                Log.debug("The qualified path " + key + " appears multiple times.",
                        IterablePath.class.getName());
            } else {
                pMap.put(key, entry);
            }
        }
    }
    return new IterablePath(paths, pMap);
}

From source file:cane.brothers.e4.commander.utils.PathUtils.java

/**
 * Root path have no file name./*from w ww.  j a v a 2  s  .  c o m*/
 * 
 * TODO rework extra symbols
 * 
 * @param path
 * @return file name
 */
public static String getFileName(Path path) {
    String pathString = null;
    if (path != null) {
        if (path.getFileName() != null) {
            pathString = path.getFileName().toString();
        } else {
            pathString = path.toString();
        }
    }
    return pathString;
}

From source file:io.github.retz.executor.FileManager.java

private static void fetchHTTPFile(String file, String dest) throws IOException {
    URL url = new URL(file);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    conn.setDoOutput(true);//from   ww  w. j  ava  2s. c  o m
    java.nio.file.Path path = Paths.get(file).getFileName();
    if (path == null) {
        throw new FileNotFoundException(file);
    }
    String filename = path.toString();
    InputStream input = null;
    try (FileOutputStream output = new FileOutputStream(dest + "/" + filename)) {
        input = conn.getInputStream();
        byte[] buffer = new byte[65536];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        LOG.debug(e.getMessage());
        throw e;
    } finally {
        if (input != null)
            input.close();
    }
    conn.disconnect();
    LOG.info("Download finished: {}", file);
}

From source file:es.uvigo.ei.sing.adops.operations.running.tcoffee.TCoffeeDefaultProcessManager.java

private static String shortenPath(String pathString, File basedir) {
    final Path path = Paths.get(pathString);
    final Path pathBasedir = basedir.toPath();

    final Path relativePath = pathBasedir.relativize(path);
    final String relativePathString = relativePath.toString();

    return relativePathString.length() < pathString.length() ? relativePathString : pathString;
}

From source file:com.netflix.genie.agent.cli.UserConsole.java

/**
 * Move the log file from the current position to the given destination.
 * Refuses to move across filesystems. Moving within the same filesystem should not invalidate any open descriptors.
 *
 * @param destinationPath destination path
 * @throws IOException if source and destination are on different filesystem devices, if destination exists, or if
 *                     the move fails.// w ww . jav a2 s .co  m
 */
public static synchronized void relocateLogFile(final Path destinationPath) throws IOException {

    final Path sourcePath = CURRENT_LOG_FILE_PATH.get();
    final Path destinationAbsolutePath = destinationPath.toAbsolutePath();

    if (!Files.exists(sourcePath)) {
        throw new IOException("Log file does not exists: " + sourcePath.toString());
    } else if (Files.exists(destinationAbsolutePath)) {
        throw new IOException("Destination already exists: " + destinationAbsolutePath.toString());
    } else if (!sourcePath.getFileSystem().provider()
            .equals(destinationAbsolutePath.getFileSystem().provider())) {
        throw new IOException("Source and destination are not in the same filesystem");
    }

    Files.move(sourcePath, destinationAbsolutePath);
    CURRENT_LOG_FILE_PATH.set(destinationAbsolutePath);

    getLogger().info("Agent log file relocated to: " + getLogFilePath());
}

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

public static List<String> readAllLines(Path path) {
    try {//  w w w  . j  a  v  a2  s.c o m
        return path.toString().endsWith(".gz") ? GZIPFiles.readAllLines(path)
                : path.toString().endsWith(".bz2") ? BZIP2Files.readAllLines(path) : _readAllLines(path);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.sonar.it.scanner.msbuild.TestUtils.java

public static void runMSBuild(Orchestrator orch, Path projectDir, String... arguments) {
    String msBuildPathStr = orch.getConfiguration().getString(MSBUILD_PATH,
            "C:\\Program Files (x86)\\MSBuild\\14.0\\bin\\MSBuild.exe");
    Path msBuildPath = Paths.get(msBuildPathStr).toAbsolutePath();
    if (!Files.exists(msBuildPath)) {
        throw new IllegalStateException("Unable to find MSBuild at " + msBuildPath.toString()
                + ". Please configure property '" + MSBUILD_PATH + "'");
    }//from   w ww .  jav a 2  s  .  co m

    int r = CommandExecutor.create().execute(
            Command.create(msBuildPath.toString()).addArguments(arguments).setDirectory(projectDir.toFile()),
            60 * 1000);
    assertThat(r).isEqualTo(0);
}

From source file:api.startup.PDFIndexer.java

/**
 * Indexes a single document and writes it to the given index writer
 * @param writer - the index writer to writer
 * @param metadata - the document/*from  w  w w. j  a  v a2 s  . co m*/
 * @throws IOException
 */
static void indexDoc(IndexWriter writer, DocumentMetadata metadata) throws IOException {
    Path file = Paths.get(metadata.getFilename());
    try {
        Document doc = new Document();

        Field pathField = new StringField(Constants.FIELD_PATH, file.toString(), Field.Store.YES);
        doc.add(pathField);

        // Add Document metadata //
        doc.add(new StringField(Constants.FIELD_AUTHOR, metadata.getAuthor(), Field.Store.YES));
        doc.add(new StringField(Constants.FIELD_TITLE, metadata.getTitle(), Field.Store.YES));
        doc.add(new StringField(Constants.FIELD_CONFERENCE, metadata.getConference(), Field.Store.YES));
        // End of Document Metadata //

        Field modified = new LongField(Constants.FIELD_MODIFIED, Files.getLastModifiedTime(file).toMillis(),
                Field.Store.YES);
        doc.add(modified);

        PDFTextExtractor extractor = new PDFTextExtractor();
        // Get the string contents
        String textContents = extractor.extractText(file.toString());

        // Store the string contents
        FieldType contentsType = new FieldType();
        contentsType.setStored(true);
        contentsType.setTokenized(true);
        contentsType.setStoreTermVectors(true);
        contentsType.setStoreTermVectorPositions(true);
        contentsType.setStoreTermVectorPayloads(true);
        contentsType.setStoreTermVectorOffsets(true);
        contentsType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
        Field contents = new Field(Constants.FIELD_CONTENTS, textContents, contentsType);
        doc.add(contents);

        if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
            // New index, so we just add the document (no old document can be there):
            log.info("adding " + file + " to index");
            writer.addDocument(doc);
        } else {
            // Existing index (an old copy of this document may have been indexed) so
            // we use updateDocument instead to replace the old one matching the exact
            // path, if present:
            log.info("updating " + file + " in index");
            writer.updateDocument(new Term(Constants.FIELD_PATH, file.toString()), doc);
        }
    } catch (IOException e) {
        log.error("Failed to read file " + metadata.getFilename());
    }

}