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.nwn.NwnFileHandler.java

/**
 * Extracts contents of given file to provided directory
 * @param file File to extract//from w w w. j a  v  a2s .  c  o  m
 * @param dest Location to extract to
 * @return True if extract success, False if extract failed
 */
public static boolean extractFile(Path file, Path dest) {
    if (getFileExtension(file.toString()).equals("zip")) {
        try {
            ZipFile zipFile = new ZipFile(file.toString());
            if (zipFile.isEncrypted()) {
                System.out.println(
                        "Cannot extract from " + file.getFileName().toString() + ": Password required.");
                return false;
            } else {
                zipFile.extractAll(dest.toString());
            }
        } catch (ZipException ex) {
            ex.printStackTrace();
            return false;
        }
    } else if (getFileExtension(file.toString()).equals("rar")) {//todo: finish
        Archive a = null;
        try {
            a = new Archive(new FileVolumeManager(file.toFile()));
        } catch (RarException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (a != null) {
            a.getMainHeader().print();
            FileHeader fh = a.nextFileHeader();
            while (fh != null) {
                try {
                    File out = new File(dest.toString() + File.separator + fh.getFileNameString().trim());
                    System.out.println(out.getAbsolutePath());
                    FileOutputStream os = new FileOutputStream(out);
                    a.extractFile(fh, os);
                    os.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RarException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fh = a.nextFileHeader();
            }
        }
    }
    return true;
}

From source file:com.textocat.textokit.commons.consumer.AnnotationPerLineWriter.java

public static AnalysisEngineDescription createDescription(String targetTypeName, Path outputDir,
        String outputFileSuffix) throws ResourceInitializationException {
    return AnalysisEngineFactory.createEngineDescription(AnnotationPerLineWriter.class, PARAM_TARGET_TYPE,
            targetTypeName, PARAM_OUTPUT_DIR, outputDir.toString(), PARAM_OUTPUT_FILE_SUFFIX, outputFileSuffix);
}

From source file:company.gonapps.loghut.utils.FileUtils.java

public static void rmdir(Path directoryPath, DirectoryStream.Filter<Path> ignoringFilter)
        throws NotDirectoryException, IOException {
    if (!directoryPath.toFile().isDirectory())
        throw new NotDirectoryException(directoryPath.toString());

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directoryPath)) {
        List<Path> ignoredPaths = new LinkedList<>();

        for (Path path : directoryStream) {
            if (!ignoringFilter.accept(path))
                return;
            ignoredPaths.add(path);/*from  www  .  j a  v a 2  s  .  c  o m*/
        }

        for (Path ignoredPath : ignoredPaths) {
            Files.delete(ignoredPath);
        }

        Files.delete(directoryPath);
    }
}

From source file:org.cyclop.test.AbstractTestCase.java

private static void setupHistory() throws Exception {
    Path tempPath = FileSystems.getDefault().getPath("target", "cyclop-history-test");
    rmdir(tempPath);//from  www. j  av a  2 s.  com
    Files.createDirectory(tempPath);
    System.getProperties().setProperty("fileStore.folder", tempPath.toString());
}

From source file:com.geewhiz.pacify.utils.FileUtils.java

/**
 * /*w  ww .  j  av a2 s  . c  o  m*/
 * @param relativePath
 * @param regEx
 *            file separator should be unix file separator
 * @return
 */
public static Boolean matches(Path relativePath, String regEx) {
    // we need to convert it, otherwise we have to mess around with
    // backslash quoting and regex
    String unixFileformat = FilenameUtils.separatorsToUnix(relativePath.toString());
    return Pattern.matches(regEx, unixFileformat);
}

From source file:com.spectralogic.ds3cli.Main.java

private static void configureLogging(final Level consoleLevel, final Level fileLevel) {

    final LoggerContext loggerContext = LOG.getLoggerContext();
    loggerContext.reset();/*  www .jav a  2  s  .com*/

    // set root log to the most permissive filter (affects performance big time (JAVACLI-90))
    final int lowestLogLevel = Math.min(consoleLevel.toInt(), fileLevel.toInt());
    LOG.setLevel(Level.toLevel(lowestLogLevel));

    if (!consoleLevel.equals(Level.OFF)) {
        // create and add console appender
        final PatternLayoutEncoder consoleEncoder = new PatternLayoutEncoder();
        consoleEncoder.setContext(loggerContext);
        consoleEncoder.setPattern(LOG_FORMAT_PATTERN);
        consoleEncoder.start();

        final ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
        consoleAppender.setContext(loggerContext);
        consoleAppender.setName("STDOUT");
        consoleAppender.setEncoder(consoleEncoder);

        final ThresholdFilter consoleFilter = new ThresholdFilter();
        consoleFilter.setLevel(consoleLevel.levelStr);
        consoleFilter.setName(consoleLevel.levelStr);
        consoleFilter.start();
        consoleAppender.addFilter(consoleFilter);

        consoleAppender.start();
        LOG.addAppender(consoleAppender);
    }

    if (!fileLevel.equals(Level.OFF)) {
        // create file appender only if needed.
        // if done in the xml, it will create an empty file
        final RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
        final FixedWindowRollingPolicy sizeBasedRollingPolicy = new FixedWindowRollingPolicy();
        final SizeBasedTriggeringPolicy<Object> sizeBasedTriggeringPolicy = new SizeBasedTriggeringPolicy<>();

        fileAppender.setContext(loggerContext);
        sizeBasedTriggeringPolicy.setContext(loggerContext);
        sizeBasedRollingPolicy.setContext(loggerContext);
        fileAppender.setRollingPolicy(sizeBasedRollingPolicy);
        sizeBasedRollingPolicy.setParent(fileAppender);
        sizeBasedRollingPolicy.setMinIndex(0);
        sizeBasedRollingPolicy.setMaxIndex(99);

        final Path logFilePath = FileSystems.getDefault().getPath(LOG_DIR, LOG_FILE_NAME);
        fileAppender.setFile(logFilePath.toString());
        sizeBasedRollingPolicy.setFileNamePattern(LOG_DIR + LOG_ARCHIVE_FILE_PATTERN);
        sizeBasedRollingPolicy.start();

        sizeBasedTriggeringPolicy.setMaxFileSize("10MB");
        sizeBasedTriggeringPolicy.start();

        final PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
        fileEncoder.setContext(loggerContext);
        fileEncoder.setPattern(LOG_FORMAT_PATTERN);
        fileEncoder.start();

        fileAppender.setTriggeringPolicy((TriggeringPolicy) sizeBasedTriggeringPolicy);
        fileAppender.setRollingPolicy(sizeBasedRollingPolicy);
        fileAppender.setEncoder(fileEncoder);
        fileAppender.setName("LOGFILE");
        sizeBasedRollingPolicy.start();

        final ThresholdFilter fileFilter = new ThresholdFilter();
        fileFilter.setLevel(fileLevel.levelStr);
        fileFilter.setName(fileLevel.levelStr);
        fileFilter.start();
        fileAppender.addFilter(fileFilter);

        LOG.addAppender((Appender) fileAppender);
        fileAppender.start();
    }
}

From source file:io.cloudslang.maven.compiler.CloudSlangMavenCompiler.java

private static Map<String, byte[]> getSourceFilesForDependencies(String dependency) throws IOException {
    Path path = Paths.get(dependency);
    if (!Files.exists(path) || !path.toString().toLowerCase().endsWith(".jar")) {
        return Collections.emptyMap();
    }/*from ww w  .j  a v a 2  s . c  o  m*/

    Map<String, byte[]> sources = new HashMap<>();

    try (JarFile jar = new JarFile(dependency)) {
        Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry file = (JarEntry) enumEntries.nextElement();
            if ((file == null) || (file.isDirectory()) || (!file.getName().endsWith(".sl.yaml")
                    && !file.getName().endsWith(".sl") && !file.getName().endsWith(".sl.yml"))) {
                continue;
            }

            byte[] bytes;
            try (InputStream is = jar.getInputStream(file)) {
                bytes = IOUtils.toByteArray(is);
                sources.put(file.getName(), bytes);
            }
        }
    }

    return sources;
}

From source file:org.mortbay.jetty.load.generator.starter.AbstractLoadGeneratorStarter.java

protected static String writeAsJsonTmp(Resource resource) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    Path tmpPath = Files.createTempFile("profile", ".tmp");
    objectMapper.writeValue(tmpPath.toFile(), resource);
    return tmpPath.toString();
}

From source file:de.elomagic.carafile.client.CaraFileUtils.java

/**
 * Creates a meta file from the given file.
 *
 * @param path Path of the file//from  ww w.java 2 s  . c  om
 * @param filename Real name of the file because it can differ from path parameter
 * @return
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static final MetaData createMetaData(final Path path, final String filename)
        throws IOException, GeneralSecurityException {
    if (Files.notExists(path)) {
        throw new FileNotFoundException("File " + path.toString() + " not found!");
    }

    if (Files.isDirectory(path)) {
        throw new IllegalArgumentException("Not a file: " + path.toString());
    }

    MetaData md = new MetaData();
    md.setSize(Files.size(path));
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);

    try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ);
            BufferedInputStream bin = new BufferedInputStream(in)) {
        MessageDigest mdComplete = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1);

        byte[] buffer = new byte[DEFAULT_PIECE_SIZE];
        int bytesRead;

        while ((bytesRead = bin.read(buffer)) > 0) {
            mdComplete.update(buffer, 0, bytesRead);

            ChunkData chunk = new ChunkData(
                    DigestUtils.sha1Hex(new ByteArrayInputStream(buffer, 0, bytesRead)));
            md.addChunk(chunk);
        }

        String sha1 = Hex.encodeHexString(mdComplete.digest());
        md.setId(sha1);
    }

    return md;
}

From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java

private static void updateDigest(Path root, MessageDigest sourceDigest, Path soyFilePath) throws IOException {
    sourceDigest.update(soyFilePath.toString().getBytes(TEXT_DIGEST_CHARSET));
    final Path soyFile = root.resolve(soyFilePath);
    sourceDigest.update(Longs.toByteArray(Files.size(soyFile)));
    sourceDigest.update(Longs.toByteArray(Files.getLastModifiedTime(soyFile).toMillis()));
}