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:net.certiv.antlr.project.util.Utils.java

/**
 * Clears (deletes) all files from the given directory.
 * // ww w. jav a2  s. c o m
 * @param dir
 *            the directory to clear
 * @return true if all files were successfully deleted
 * @throws IOException
 */
public static boolean deleteAllFiles(File dir) throws IOException {
    if (dir == null)
        throw new IllegalArgumentException("Directory cannot be null");
    if (!dir.exists() || !dir.isDirectory())
        throw new IOException("Directory must exist");

    DirectoryStream<Path> ds = Files.newDirectoryStream(dir.toPath());
    int del = 0;
    int tot = 0;
    for (Path p : ds) {
        File f = p.toFile();
        String name = f.getName();
        if (f.isFile()) {
            tot++;
            boolean ok = f.delete();
            if (ok) {
                del++;
            } else {
                Log.warn(Utils.class, "Failed to delete: " + name);
            }
        }
    }
    Log.info(Utils.class, "Deleted " + del + " of " + tot + " files");
    return del == tot;
}

From source file:com.sunteng.flume.source.tail.TailFileEventReader.java

public static String getFileKey(File file) {
    BasicFileAttributes basicAttr;
    try {//from   w w w . ja  va2s.com
        basicAttr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
    } catch (IOException e) {
        return new String();
    }
    Object obj = basicAttr.fileKey();
    if (obj == null) {
        return new String();
    }
    return obj.toString();
}

From source file:maspack.fileutil.SafeFileUtils.java

public static void copyDirectory(File srcDir, File destDir, int options) throws IOException {
    Files.walkFileTree(srcDir.toPath(), new CopyFileVisitor(destDir.toPath()));
}

From source file:com.github.blindpirate.gogradle.util.IOUtils.java

public static Path ensureDirExistAndWritable(Path path) {
    Assert.isTrue(path.isAbsolute(), "path must be absolute!");
    File dir = path.toFile();
    IOUtils.forceMkdir(dir);/*from   www . j  a v  a 2  s .  c  o  m*/
    Assert.isTrue(Files.isWritable(dir.toPath()), "Cannot write to directory:" + path);
    return path;
}

From source file:com.ibm.wala.cast.js.nodejs.NodejsRequireTargetSelector.java

/**
 * NODE_MODULES_PATHS(START)/*ww w.ja va 2  s. co  m*/
 * 1. let PARTS = path split(START)
 * 2. let I = count of PARTS - 1
 * 3. let DIRS = []
 * 4. while I &gt;= 0,
 *    a. if PARTS[I] = "node_modules" CONTINUE
 *    b. DIR = path join(PARTS[0 .. I] + "node_modules")
 *    c. DIRS = DIRS + DIR
 *    d. let I = I - 1
 * 5. return DIRS
 * 
 * @param d
 * @throws IOException
 */
private static List<File> nodeModulePaths(File rootDir, File d) throws IOException {
    LinkedList<File> dirs = new LinkedList<>();

    while (d.getCanonicalPath().startsWith(rootDir.getCanonicalPath()) && d.toPath().getNameCount() > 0) {
        // 4.a.
        if (!d.getName().equals("node_modules")) {
            // 4.b. and 4.c.
            dirs.add(new File(d, "node_modules"));
        }

        // 4.d.
        d = d.getParentFile();
    }

    return dirs;
}

From source file:net.nifheim.beelzebu.coins.common.utils.dependencies.DependencyManager.java

private static File downloadDependency(File libDir, Dependency dependency) throws Exception {
    String fileName = dependency.name().toLowerCase() + "-" + dependency.getVersion() + ".jar";

    File file = new File(libDir, fileName);
    if (file.exists()) {
        return file;
    }/*w  w w. j a v  a2 s .  c om*/

    URL url = new URL(dependency.getUrl());

    core.getMethods().log("Dependency '" + fileName + "' could not be found. Attempting to download.");
    try (InputStream in = url.openStream()) {
        Files.copy(in, file.toPath());
    }

    if (!file.exists()) {
        throw new IllegalStateException("File not present. - " + file.toString());
    } else {
        core.getMethods().log("Dependency '" + fileName + "' successfully downloaded.");
        return file;
    }
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

/**
 * Given a markdown document to search, this checks to see if the specified tables
 * have all of the expected fields listed.
 * Match is a "search", and not an "equals" match.
 *
 * @param doc           markdown document file to inspect
 * @param fieldsByTable map of table name (header) to field names expected
 *                      to be found in that table.
 * @throws IOException if the markdown document could not be read
 *///from w  w  w  .  j a v a2  s. c o m
private static void verifyMarkdownContainsFieldsInTables(File doc, Map<String, Set<String>> fieldsByTable)
        throws IOException {
    //TODO: This method is too complex, split it up in smaller methods to increase readability
    final List<String> lines = Files.readAllLines(doc.toPath(), Charset.defaultCharset());
    final Map<String, Set<String>> fieldsLeftByTable = Maps.newHashMap();
    for (Map.Entry<String, Set<String>> entry : fieldsByTable.entrySet()) {
        fieldsLeftByTable.put(entry.getKey(), Sets.newHashSet(entry.getValue()));
    }
    String inTable = null;
    for (String line : lines) {
        // If we've found every field we care about, quit early
        if (fieldsLeftByTable.isEmpty()) {
            return;
        }

        // Transition to a new table if we encounter a header
        final String currentHeader = getTableHeader(line);
        if (inTable == null || currentHeader != null) {
            inTable = currentHeader;
        }

        // If we're in a table that we care about, inspect this potential table row
        if (inTable != null && fieldsLeftByTable.containsKey(inTable)) {
            // If we're still in a table, read the row and check for the field name
            //  NOTE: If there was at least one pipe, then there's at least 2 fields
            String[] parts = line.split("\\|");
            if (parts.length > 1) {
                final String fieldName = parts[1];
                final Set<String> fieldsLeft = fieldsLeftByTable.get(inTable);
                // Mark the field as found and if this table has no more fields to find,
                //  remove it from the "fieldsLeftByTable" map to mark the table as done
                Iterator<String> fieldIt = fieldsLeft.iterator();
                while (fieldIt.hasNext()) {
                    String fieldLeft = fieldIt.next();
                    if (fieldName.contains(fieldLeft))
                        fieldIt.remove();
                }
                if (fieldsLeft.isEmpty()) {
                    fieldsLeftByTable.remove(inTable);
                }
            }
        }
    }

    // After reading the file, if there were still types, fail
    if (!fieldsLeftByTable.isEmpty()) {
        fail(String.format("Markdown file '%s' did not contain expected fields (by table): %s", doc,
                fieldsLeftByTable));
    }
}

From source file:eu.eubrazilcc.lvl.service.io.DatasetWriter.java

private static File sequence2dataset(final Dataset dataset) {
    final Metadata metadata = dataset.getMetadata();
    final String filter = isNotBlank(metadata.getTarget().getFilter())
            ? metadata.getTarget().getFilter().trim().toLowerCase()
            : EXPORT_DEFAULT;//from   w  w  w . j  av a2  s .co  m
    File outfile = null;
    if (EXPORT_DEFAULT.equals(filter) || EXPORT_FASTA.equals(filter)) {
        final String compression = getCompression(metadata.getTarget().getCompression());
        final List<File> files = from(metadata.getTarget().getIds()).transform(new Function<String, File>() {
            @Override
            public File apply(final String id) {
                final SequenceDAO<? extends Sequence> dao = fromString(metadata.getTarget().getCollection());
                final Sequence sequence = dao
                        .find(SequenceKey.builder().parse(id, ID_FRAGMENT_SEPARATOR, NOTATION_LONG));
                checkState(sequence != null, "Sequence not found: " + id);
                return openGenBankFile(sequence, GB_SEQ_XML);
            }
        }).toList();
        try {
            final File baseOutputDir = new File(CONFIG_MANAGER.getLocalCacheDir(),
                    DatasetWriter.class.getSimpleName());
            baseOutputDir.mkdirs();
            final File outputDir = createTempDirectory(baseOutputDir.toPath(), "dataset-").toFile();
            if (EXPORT_FASTA.equals(filter)) {
                if (files.size() == 1) {
                    outfile = writeFastaSequence(files.get(0), outputDir, compression);
                } else {
                    outfile = writeFastaSequences(files, outputDir, compression);
                }
                dataset.getMetadata().getTags().add("fasta");
            } else {
                if (files.size() == 1) {
                    outfile = writeGbXmlSequence(files.get(0), outputDir, compression);
                } else {
                    outfile = writeGbXmlSequences(files, outputDir, compression);
                }
                dataset.getMetadata().getTags().add("ncbi_xml");
            }
        } catch (IOException e) {
            throw new IllegalStateException("Failed to copy sequence", e);
        }
    } else {
        throw new IllegalArgumentException("Unsupported filter: " + metadata.getTarget().getFilter());
    }
    return outfile;
}

From source file:com.diffplug.gradle.FileMisc.java

/** Concats the first files and writes them to the last file. */
public static void concat(Iterable<File> toMerge, File dst) throws IOException {
    try (FileChannel dstChannel = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
        for (File file : toMerge) {
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                FileChannel channel = raf.getChannel();
                dstChannel.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, raf.length()));
            }//w  ww. j  a v a 2s  .  c  om
        }
    }
}

From source file:com.buaa.cfs.utils.IOUtils.java

/**
 * Return the complete list of files in a directory as strings.<p/>
 * <p>//from  w  w w .j  ava  2 s. c  o m
 * This is better than File#listDir because it does not ignore IOExceptions.
 *
 * @param dir    The directory to list.
 * @param filter If non-null, the filter to use when listing this directory.
 *
 * @return The list of files in the directory.
 *
 * @throws IOException On I/O error
 */
public static List<String> listDirectory(File dir, FilenameFilter filter) throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir.toPath())) {
        for (Path entry : stream) {
            String fileName = entry.getFileName().toString();
            if ((filter == null) || filter.accept(dir, fileName)) {
                list.add(fileName);
            }
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
    return list;
}