Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:azkaban.project.FlowLoaderUtils.java

/**
 * Sets props in flow yaml file./*  w w w  .j  a  v  a2s . c om*/
 *
 * @param path the flow or job path delimited by ":", e.g. "flow:subflow1:subflow2:job3"
 * @param flowFile the flow yaml file
 * @param prop the props to set
 */
public static void setPropsInYamlFile(final String path, final File flowFile, final Props prop) {
    final DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    final NodeBean nodeBean = FlowLoaderUtils.setPropsInNodeBean(path, flowFile, prop);
    try (final BufferedWriter writer = Files.newBufferedWriter(flowFile.toPath(), StandardCharsets.UTF_8)) {
        new Yaml(options).dump(nodeBean, writer);
    } catch (final IOException e) {
        throw new ProjectManagerException("Failed to set properties in flow file " + flowFile.getName());
    }
}

From source file:io.druid.java.util.common.CompressionUtils.java

public static void validateZipOutputFile(String sourceFilename, final File outFile, final File outDir)
        throws IOException {
    // check for evil zip exploit that allows writing output to arbitrary directories
    final File canonicalOutFile = outFile.getCanonicalFile();
    final String canonicalOutDir = outDir.getCanonicalPath();
    if (!canonicalOutFile.toPath().startsWith(canonicalOutDir)) {
        throw new ISE("Unzipped output path[%s] of sourceFile[%s] does not start with outDir[%s].",
                canonicalOutFile, sourceFilename, canonicalOutDir);
    }/*w w w  .jav  a 2  s.  c  o m*/
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean archiveDirZip(final File dir, final File dest) {
    final Path dirPath = dir.toPath();
    final String parent = dir.getName();
    Map<String, String> env = Maps.newHashMap();
    env.put("create", "true");
    URI uri = dest.toURI();//from   w  w  w. j a v a  2 s.c om

    try {
        uri = new URI("jar:" + uri.getScheme(), uri.getPath(), null);
    } catch (Exception e) {
        return false;
    }

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Files.createDirectory(zipfs.getPath(parent));

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, zipfs.getPath(parent, dirPath.relativize(file).toString()),
                                StandardCopyOption.REPLACE_EXISTING);

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Files.createDirectory(zipfs.getPath(parent, dirPath.relativize(dir).toString()));

                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                Files.copy(file.toPath(), zipfs.getPath(parent, file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;/*w  w w. j av a  2 s  . co  m*/
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}

From source file:net.sf.jabref.gui.exporter.AutoSaveManager.java

/**
 * Perform an autosave.//from www .j  av  a2  s.  c o  m
 * @param panel The BasePanel to autosave for.
 * @return true if successful, false otherwise.
 */
private static boolean autoSave(BasePanel panel) {
    File databaseFile = panel.getBibDatabaseContext().getDatabaseFile();
    File backupFile = AutoSaveManager.getAutoSaveFile(databaseFile);
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withMakeBackup(false)
                .withEncoding(panel.getBibDatabaseContext().getMetaData().getEncoding());

        BibDatabaseWriter databaseWriter = new BibtexDatabaseWriter(FileSaveSession::new);
        SaveSession ss = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);
        ss.commit(backupFile.toPath());
    } catch (SaveException e) {
        LOGGER.error("Problem with automatic save", e);
        return false;
    }
    return true;
}

From source file:com.btisystems.pronx.ems.App.java

private static void saveNotificationRegistry(final String packageName, final NotificationMeta meta) {
    final File notificationRegistryDoc = getNotificationRegistryDocumentName(packageName);
    final File notificationRegistryDir = notificationRegistryDoc.getParentFile();
    if (Files.notExists(notificationRegistryDir.toPath())) {
        notificationRegistryDir.mkdirs();
    }//from ww  w .  j  av a  2  s .co  m
    try (XMLEncoder encoder = new XMLEncoder(
            new BufferedOutputStream(new FileOutputStream(notificationRegistryDoc)))) {
        encoder.writeObject(meta);
        encoder.writeObject(meta);
    } catch (final Exception e) {
        LOG.error("Exception saving Notification Registry: {}", e.getMessage(), e);
    }
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFile(File file, String pkg, Set<Class<?>> pkgModules)
        throws Exception {
    Assert.assertTrue("'checkstyle-metadata.xml' must exist in eclipsecs in inside " + pkg, file.exists());

    final String input = new String(Files.readAllBytes(file.toPath()), UTF_8);
    final Document document = XmlUtil.getRawXml(file.getAbsolutePath(), input, input);

    final NodeList ruleGroups = document.getElementsByTagName("rule-group-metadata");

    Assert.assertTrue(pkg + " checkstyle-metadata.xml must contain only one rule group",
            ruleGroups.getLength() == 1);

    for (int position = 0; position < ruleGroups.getLength(); position++) {
        final Node ruleGroup = ruleGroups.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(ruleGroup);

        validateEclipseCsMetaXmlFileRules(pkg, pkgModules, children);
    }/*ww w  .  ja v  a 2  s.  c o  m*/

    for (Class<?> module : pkgModules) {
        Assert.fail("Module not found in " + pkg + " checkstyle-metadata.xml: " + module.getCanonicalName());
    }
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

/**
 * Extracts the country source from the feature list of a GenBank DNA sequence file.
 * @param file GenBank sequence file.//from   ww w  .ja v a 2 s . co m
 * @return the value of the country source feature if exists, otherwise {@code null}.
 * @throws Exception if an error occurs.
 */
public static @Nullable String countryFeature(final File file) throws Exception {
    String country = null;
    final BufferedReader reader = newBufferedReader(file.toPath(), DEFAULT_CHARSET);
    boolean featuresFound = false, sourceFound = false;
    String line = null;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("ORIGIN") || line.startsWith("CONTIG      ")) {
            break;
        } else if (!featuresFound) {
            if (line.startsWith("FEATURES             Location/Qualifiers")) {
                featuresFound = true;
            }
        } else if (!sourceFound) {
            if (line.startsWith("     source          ")) {
                sourceFound = true;
            }
        } else {
            if (line.startsWith("                     /country=")) {
                final Pattern pattern = Pattern.compile("\"(.*?)\"");
                final Matcher matcher = pattern.matcher(line.substring(30));
                if (matcher.find()) {
                    country = matcher.group(1);
                }
            }
        }
    }
    return country;
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static String getMimeType(File file) {

    String mimetype = null;/*  w  w w  .j  av  a  2 s  .c o  m*/
    try {
        mimetype = Files.probeContentType(file.toPath());
    } catch (IOException ex) {

    }

    if (mimetype == null) {
        mimetype = "unknown";
    }
    return mimetype;
}

From source file:com.simiacryptus.util.Util.java

/**
 * Path to string./*from  w w  w.j a va2  s .c  o  m*/
 *
 * @param from the from
 * @param to   the to
 * @return the string
 */
public static String pathTo(@javax.annotation.Nonnull final File from,
        @javax.annotation.Nonnull final File to) {
    return from.toPath().relativize(to.toPath()).toString().replaceAll("\\\\", "/");
}