Example usage for java.nio.file Path toFile

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

Introduction

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

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:net.certiv.antlr.project.util.Utils.java

/**
 * Creates a new, unique directory, with the given prefix, in the system temp directory.
 * /*from w  w  w  .ja  v a2s.c o  m*/
 * @return a File representing the new directory
 * @throws IOException
 */
public static File createTmpDir() throws IOException {
    Path p = null;
    if (Strings.pathSepStr == Strings.STD_SEPARATOR) {
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
        FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
        p = Files.createTempDirectory("ReGen", attr);
    } else {
        p = Files.createTempDirectory("ReGen");
    }
    return p.toFile();
}

From source file:com.blackducksoftware.integration.hub.detect.util.DetectZipUtil.java

public static void unzip(File zip, File dest, Charset charset) throws IOException {
    Path destPath = dest.toPath();
    try (ZipFile zipFile = new ZipFile(zip, ZipFile.OPEN_READ, charset)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Path entryPath = destPath.resolve(entry.getName());
            if (!entryPath.normalize().startsWith(dest.toPath()))
                throw new IOException("Zip entry contained path traversal");
            if (entry.isDirectory()) {
                Files.createDirectories(entryPath);
            } else {
                Files.createDirectories(entryPath.getParent());
                try (InputStream in = zipFile.getInputStream(entry)) {
                    try (OutputStream out = new FileOutputStream(entryPath.toFile())) {
                        IOUtils.copy(in, out);
                    }/* w ww. j av a2s .c  o  m*/
                }
            }
        }
    }
}

From source file:com.scooter1556.sms.server.utilities.DatabaseUtils.java

public static boolean createNewDatabaseFile(String db, int oldVersion, int newVersion) {
    if (SettingsService.getInstance().getDataDirectory() == null) {
        return false;
    }//www .j  a  v a 2  s.  co m

    try {
        Path oldDb = Paths.get(SettingsService.getInstance().getDataDirectory() + "/db/" + db.toLowerCase()
                + "." + oldVersion + ".h2.db");
        Path newDb = Paths.get(SettingsService.getInstance().getDataDirectory() + "/db/" + db.toLowerCase()
                + "." + newVersion + ".h2.db");

        // Copy old database file to a new file and remove the old one
        Files.copy(oldDb, newDb);

        // Remove old database file
        return oldDb.toFile().delete();
    } catch (IOException ex) {
        return false;
    }
}

From source file:com.facebook.buck.zip.Unzip.java

/**
 * Unzips a file to a destination and returns the paths of the written files.
 *///from   w  w  w  . j a  v a  2  s .c o m
public static ImmutableList<Path> extractZipFile(Path zipFile, ProjectFilesystem filesystem, Path relativePath,
        ExistingFileMode existingFileMode) throws IOException {
    // if requested, clean before extracting
    if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) {
        try (ZipFile zip = new ZipFile(zipFile.toFile())) {
            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                filesystem.deleteRecursivelyIfExists(relativePath.resolve(entry.getName()));
            }
        }
    }
    ImmutableList.Builder<Path> filesWritten = ImmutableList.builder();
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = entry.getName();
            Path target = relativePath.resolve(fileName);

            // TODO(bolinfest): Keep track of which directories have already been written to avoid
            // making unnecessary Files.createDirectories() calls. In practice, a single zip file will
            // have many entries in the same directory.

            if (entry.isDirectory()) {
                // Create the directory and all its parent directories
                filesystem.mkdirs(target);
            } else {
                // Create parent folder
                filesystem.createParentDirs(target);

                filesWritten.add(target);
                // Write file
                try (InputStream is = zip.getInputStream(entry)) {
                    if (entry.isUnixSymlink()) {
                        filesystem.createSymLink(target,
                                filesystem.getPath(new String(ByteStreams.toByteArray(is), Charsets.UTF_8)),
                                /* force */ true);
                    } else {
                        try (OutputStream out = filesystem.newFileOutputStream(target)) {
                            ByteStreams.copy(is, out);
                        }
                    }
                }

                // restore mtime for the file
                filesystem.resolve(target).toFile().setLastModified(entry.getTime());

                // TODO(shs96c): Implement what the comment below says we should do.
                //
                // Sets the file permissions of the output file given the information in {@code entry}'s
                // extra data field. According to the docs at
                // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
                // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
                // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
                //
                // <pre>
                //    The following is the layout of the ASi extra block for Unix.  The
                //    local-header and central-header versions are identical.
                //    (Last Revision 19960916)
                //
                //    Value         Size        Description
                //    -----         ----        -----------
                //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
                //   TSize         Short       total data size for this block
                //   CRC           Long        CRC-32 of the remaining data
                //   Mode          Short       file permissions
                //   SizDev        Long        symlink'd size OR major/minor dev num
                //   UID           Short       user ID
                //   GID           Short       group ID
                //   (var.)        variable    symbolic link filename
                //
                //   Mode is the standard Unix st_mode field from struct stat, containing
                //   user/group/other permissions, setuid/setgid and symlink info, etc.
                // </pre>
                //
                // From the stat man page, we see that the following mask values are defined for the file
                // permissions component of the st_mode field:
                //
                // <pre>
                //   S_ISUID   0004000   set-user-ID bit
                //   S_ISGID   0002000   set-group-ID bit (see below)
                //   S_ISVTX   0001000   sticky bit (see below)
                //
                //   S_IRWXU     00700   mask for file owner permissions
                //
                //   S_IRUSR     00400   owner has read permission
                //   S_IWUSR     00200   owner has write permission
                //   S_IXUSR     00100   owner has execute permission
                //
                //   S_IRWXG     00070   mask for group permissions
                //   S_IRGRP     00040   group has read permission
                //   S_IWGRP     00020   group has write permission
                //   S_IXGRP     00010   group has execute permission
                //
                //   S_IRWXO     00007   mask for permissions for others
                //   (not in group)
                //   S_IROTH     00004   others have read permission
                //   S_IWOTH     00002   others have write permission
                //   S_IXOTH     00001   others have execute permission
                // </pre>
                //
                // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
                // but we'll check and throw if they are.
                //
                // Before we do anything, we should check the header ID. Pfft!
                //
                // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
                // values in the external file attributes of a zip entry (found in the zip's central
                // directory) assuming that the OS creating the zip was one of an enormous list that
                // includes UNIX but not Windows, it first searches for the extra fields, and if not found
                // falls through to a code path that supports MS-DOS and which stores the UNIX file
                // attributes in the upper 16 bits of the external attributes field.
                //
                // We'll support neither approach fully, but we encode whether this file was executable
                // via storing 0100 in the fields that are typically used by zip implementations to store
                // POSIX permissions. If we find it was executable, use the platform independent java
                // interface to make this unpacked file executable.

                Set<PosixFilePermission> permissions = MorePosixFilePermissions
                        .fromMode(entry.getExternalAttributes() >> 16);
                if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)) {
                    MoreFiles.makeExecutable(filesystem.resolve(target));
                }
            }
        }
    }
    return filesWritten.build();
}

From source file:controllers.ImageBrowser.java

@Util
public static void recursiveSetVisibility(Project project, Path path, boolean visible) {
    for (Path p : PathService.listPaths(path)) {
        if (p.toFile().isDirectory()) {
            recursiveSetVisibility(project, p, visible);
        } else {//from w ww  .j ava 2s  .  c o m
            DatabaseImage image = DatabaseImage.forPath(p);
            ProjectVisibleImage.setVisible(project, image, visible);
        }
    }
}

From source file:fr.pilato.elasticsearch.crawler.fs.util.FsCrawlerUtil.java

/**
 * Copy a single resource file from the classpath or from a JAR.
 * @param target The target/* w  ww.  j  av  a  2 s.  co  m*/
 * @throws IOException If copying does not work
 */
public static void copyResourceFile(String source, Path target) throws IOException, URISyntaxException {
    InputStream resource = FsCrawler.class.getResourceAsStream(source);
    FileUtils.copyInputStreamToFile(resource, target.toFile());
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** This method is used by transforms that produce new vocabulary
 * data to replace harvested data. If such a transform succeeds,
 * call this method. It renames the original harvest directory, and
 * then renames the temporary directory to become the harvest directory.
 * @param taskInfo The TaskInfo object representing the task.
 * @param transformName The name of the transform that has been done.
 * @return True iff the renaming succeeded.
 *//*from w ww  .  j  a  v  a 2 s  .c o m*/
public static boolean renameTransformTemporaryOutputPath(final TaskInfo taskInfo, final String transformName) {
    Path transformOutputPath = Paths.get(getTaskOutputPath(taskInfo, "after_" + transformName));
    Path harvestPath = Paths.get(getTaskHarvestOutputPath(taskInfo));
    Path harvestPathDestination = Paths.get(getTaskOutputPath(taskInfo, "before_" + transformName));
    try {
        // Remove any previous harvestPathDestination
        FileUtils.deleteQuietly(harvestPathDestination.toFile());
        Files.move(harvestPath, harvestPathDestination);
        Files.move(transformOutputPath, harvestPath);
    } catch (IOException e) {
        logger.error("Exception in renameTransformTemporaryOutputPath", e);
        return false;
    }
    return true;
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Delete a file or directory specified by a {@link Path}. This method uses
 * the new {@link Files} API and allows to specify a regular expression to
 * remove only files that match that expression.
 * // www .  jav a 2s  .c o  m
 * @param path
 * @param pattern
 * @throws IOException
 */
public static void deleteRecursive(Path path, final String pattern) throws IOException {

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern);

    if (!Files.exists(path))
        return;

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // try to delete the file anyway, even if its attributes
            // could not be read, since delete-only access is
            // theoretically possible
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                if (matcher.matches(dir.getFileName())) {
                    if (dir.toFile().list().length > 0) {
                        // remove even if not empty
                        FileUtils.deleteRecursive(dir);
                    } else {
                        Files.delete(dir);
                    }
                }
                return FileVisitResult.CONTINUE;
            } else {
                // directory iteration failed; propagate exception
                throw exc;
            }
        }

    });
}

From source file:controllers.ImageBrowser.java

@ModelAccess(AccessType.SET_VISIBLE)
public static void setMultipleVisible(Project project, String rootPath, String names, boolean visible) {
    for (String name : names.split(",")) {
        Path path = PathService.resolve(rootPath + "/" + name);
        if (path.toFile().isDirectory()) {
            recursiveSetVisibility(project, path, visible);
        } else {/*from w w  w .  j a  va2s. c  o m*/
            DatabaseImage image = DatabaseImage.forPath(path);
            ProjectVisibleImage.setVisible(project, image, visible);
        }
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.app.Main.java

private static void loadConfiguration() {
    Path defaultConfigPath = workingDirectory.resolve(CONFIGURATION_FILENAME);
    logger.debug("Searching for config in default filepath: " + defaultConfigPath.toAbsolutePath().toString());

    try {/*from  www. j a v a  2 s  .  c om*/
        logger.debug("Loading configuration.");

        config = new PropertiesConfiguration(defaultConfigPath.toFile());

    } catch (ConfigurationException e) {
        logger.error(e.getMessage(), e);
        logger.error("Configuration could not be loaded. Exiting...");
        System.exit(-1);
    }

    if (!(defaultConfigPath.toFile().exists() && defaultConfigPath.toFile().isFile())) {
        try {
            logger.info("Creating empty config file in working directory...");
            config.save();
            logger.debug("Saved empty configuration: " + defaultConfigPath.toAbsolutePath().toString());
        } catch (ConfigurationException e) {
            logger.error("Default configuration file could not be saved!");
            logger.error(e.getMessage(), e);
        }
    }
}