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:misc.FileHandler.java

/**
 * Creates any non-existing parent directories for the given file name path.
 * //from ww  w .j a v a2 s .c  om
 * @param fileName
 *            path to a file name. May include arbitrary many parent
 *            directories. May not be <code>null</code>.
 * @return <code>true</code>, if all parent directories were created
 *         successfully or if there were not any parent directories to
 *         create. Otherwise, <code>false</code> is returned.
 */
public static boolean makeParentDirs(Path fileName) {
    if (fileName == null) {
        throw new NullPointerException("fileName may not be null!");
    }

    boolean result = true;
    Path normalizedPath = fileName.normalize();
    Path parent = normalizedPath.getParent();

    if (parent != null) {
        result = parent.toFile().mkdirs();
    }

    return result;
}

From source file:io.sloeber.core.managers.Manager.java

/**
 * Given a platform description in a json file download and install all
 * needed stuff. All stuff is including all tools and core files and
 * hardware specific libraries. That is (on windows) inclusive the make.exe
 *
 * @param platform/*from   w ww.  j  a  va 2s . c  om*/
 * @param monitor
 * @param object
 * @return
 */
static public IStatus downloadAndInstall(ArduinoPlatform platform, boolean forceDownload,
        IProgressMonitor monitor) {

    IStatus status = downloadAndInstall(platform.getUrl(), platform.getArchiveFileName(),
            platform.getInstallPath(), forceDownload, monitor);
    if (!status.isOK()) {
        return status;
    }
    MultiStatus mstatus = new MultiStatus(status.getPlugin(), status.getCode(), status.getMessage(),
            status.getException());

    if (platform.getToolsDependencies() != null) {
        for (ToolDependency tool : platform.getToolsDependencies()) {
            monitor.setTaskName(InstallProgress.getRandomMessage());
            mstatus.add(tool.install(monitor));
        }
    }
    // On Windows install make from equations.org
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        try {
            Path makePath = Paths
                    .get(ConfigurationPreferences.getPathExtensionPath().append("make.exe").toString()); //$NON-NLS-1$
            if (!makePath.toFile().exists()) {
                Files.createDirectories(makePath.getParent());
                URL makeUrl = new URL("ftp://ftp.equation.com/make/32/make.exe"); //$NON-NLS-1$
                Files.copy(makeUrl.openStream(), makePath);
                makePath.toFile().setExecutable(true, false);

            }
        } catch (IOException e) {
            mstatus.add(new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Downloading_make_exe, e));
        }
    }

    return mstatus.getChildren().length == 0 ? Status.OK_STATUS : mstatus;

}

From source file:com.nwn.NwnFileHandler.java

/**
 * Extracts contents of given file to provided directory
 * @param file File to extract//from  www  .  java2s  . 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.opentangerine.clean.Delete.java

/**
 * Deletes file/dir under given path.//w  w  w . j  a  v a 2 s . c  o m
 * @param path Path.
 */
public void file(final Path path) {
    this.file(path.toFile());
}

From source file:caillou.company.clonemanager.gui.service.task.impl.CloneManagerIOExceptionAdvice.java

private String getErrorMessageForIOException(Path path) {
    String message;//from  w  w w .  j a  v  a  2  s .c  om

    if (path.toFile().exists() && path.toFile().isDirectory()) {
        message = ErrorMessage.VISIT_DIRECTORY_FAILED;
    } else {
        message = ErrorMessage.VISIT_FILE_FAILED;
    }
    message += path.toString();
    return message;
}

From source file:edu.jhu.hlt.acute.iterators.zip.ZipArchiveEntryByteIterator.java

/**
 * Wrap a {@link Path} object. //from   w  w w . j  av  a2 s . com
 * 
 * @throws IOException if there are issues with the underlying archive
 */
public ZipArchiveEntryByteIterator(Path p) throws IOException {
    this.zf = new ZipFile(p.toFile());
    this.iter = this.zf.getEntries();
}

From source file:com.yqboots.fss.core.support.FileItemConsumer.java

/**
 * {@inheritDoc}//from   w  w  w .  j a va2s . c  o m
 */
@Override
public void accept(final Path path) {
    final File file = path.toFile();
    final FileItem item = new FileItem();
    item.setName(file.getName());

    String relativePath = StringUtils.substringAfter(file.getPath(), root.toString());
    item.setPath(relativePath.replace("\\", "/"));
    item.setLength(file.length());
    item.setLastModifiedDate(
            LocalDateTime.ofInstant(new Date(file.lastModified()).toInstant(), ZoneId.systemDefault()));
    items.add(item);
}

From source file:com.cisco.cta.taxii.adapter.ConfigTaskTest.java

@Test
public void createsConfigDir() throws Exception {
    Path configDir = Paths.get("target/config");
    FileUtils.deleteDirectory(configDir.toFile());
    ConfigTask cfTask = new ConfigTask(configDir.toString());
    cfTask.run();// ww  w. ja  va  2s.  c  o  m

    assertTrue(Files.exists(configDir));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "application.yml")));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "logback.xml")));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "stix2cef.xsl")));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "stix2splunk.xsl")));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "stix2stix.xsl")));
    assertTrue(Files.exists(Paths.get(configDir.toString(), "taxii-response.xsl")));

}

From source file:de.ks.flatadocdb.defaults.SingleFolderGenerator.java

@Override
public Path getFolder(Repository repository, @Nullable Path ownerPath, Object object) {
    Path rootFolder = super.getFolder(repository, ownerPath, object);

    EntityDescriptor descriptor = repository.getMetaModel().getEntityDescriptor(object.getClass());
    Object naturalId = descriptor.getNaturalId(object);
    if (naturalId != null) {
        String naturalIdString = NameStripper.stripName(String.valueOf(naturalId));
        String retval = naturalIdString;
        Path targetFolder = rootFolder.resolve(retval);
        targetFolder.toFile().mkdir();
        log.trace("Using folder \"{}\" via natural id for {}", targetFolder, object);
        return targetFolder;
    } else {/*from  w w w. j a  v a2 s .  c om*/
        String hexString = parseHashCode(object);
        String retval = hexString;
        Path targetFolder = rootFolder.resolve(retval);
        targetFolder.toFile().mkdir();
        log.trace("Using folder \"{}\" via hashcode for {}", targetFolder, object);
        return targetFolder;
    }
}

From source file:heigit.ors.routing.RoutingProfile.java

public static ORSGraphHopper initGraphHopper(String osmFile, RouteProfileConfiguration config,
        RoutingProfilesCollection profiles, RoutingProfileLoadContext loadCntx) throws Exception {
    CmdArgs args = createGHSettings(osmFile, config);

    RoutingProfile refProfile = null;//ww  w.j  a  va2s  .  c om

    try {
        refProfile = profiles.getRouteProfile(RoutingProfileType.DRIVING_CAR);
    } catch (Exception ex) {
    }

    int profileId = 0;
    synchronized (lockObj) {
        profileIdentifier++;
        profileId = profileIdentifier;
    }

    long startTime = System.currentTimeMillis();

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(String.format("[%d] Profiles: '%s', location: '%s'.", profileId, config.getProfiles(),
                config.getGraphPath()));
    }

    GraphProcessContext gpc = new GraphProcessContext(config);

    ORSGraphHopper gh = new ORSGraphHopper(gpc, config.getUseTrafficInformation(), refProfile);

    ORSDefaultFlagEncoderFactory flagEncoderFactory = new ORSDefaultFlagEncoderFactory();
    gh.setFlagEncoderFactory(flagEncoderFactory);

    gh.init(args);

    // MARQ24: make sure that we only use ONE instance of the ElevationProvider across the multiple vehicle profiles
    // so the caching for elevation data will/can be reused across different vehicles. [the loadCntx is a single
    // Object that will shared across the (potential) multiple running instances]
    if (loadCntx.getElevationProvider() != null) {
        gh.setElevationProvider(loadCntx.getElevationProvider());
    } else {
        loadCntx.setElevationProvider(gh.getElevationProvider());
    }
    gh.setGraphStorageFactory(new ORSGraphStorageFactory(gpc.getStorageBuilders()));
    gh.setWeightingFactory(new ORSWeightingFactory(RealTrafficDataProvider.getInstance()));

    gh.importOrLoad();

    if (LOGGER.isInfoEnabled()) {
        EncodingManager encodingMgr = gh.getEncodingManager();
        GraphHopperStorage ghStorage = gh.getGraphHopperStorage();
        // MARQ24 MOD START
        // Same here as for the 'gh.getCapacity()' below - the 'encodingMgr.getUsedBitsForFlags()' method requires
        // the EncodingManager to be patched - and this is ONLY required for this logging line... which is IMHO
        // not worth it (and since we are not sharing FlagEncoders for mutiple vehicles this info is anyhow
        // obsolete
        //LOGGER.info(String.format("[%d] FlagEncoders: %s, bits used %d/%d.", profileId, encodingMgr.fetchEdgeEncoders().size(), encodingMgr.getUsedBitsForFlags(), encodingMgr.getBytesForFlags() * 8));
        LOGGER.info(String.format("[%d] FlagEncoders: %s, bits used [UNKNOWN]/%d.", profileId,
                encodingMgr.fetchEdgeEncoders().size(), encodingMgr.getBytesForFlags() * 8));
        // the 'getCapacity()' impl is the root cause of having a copy of the gh 'com.graphhopper.routing.lm.PrepareLandmarks'
        // class (to make the store) accessible (getLandmarkStorage()) - IMHO this is not worth it!
        // so gh.getCapacity() will be removed!
        //LOGGER.info(String.format("[%d] Capacity:  %s. (edges - %s, nodes - %s)", profileId, RuntimeUtility.getMemorySize(gh.getCapacity()), ghStorage.getEdges(), ghStorage.getNodes()));
        LOGGER.info(String.format("[%d] Capacity: [UNKNOWN]. (edges - %s, nodes - %s)", profileId,
                ghStorage.getEdges(), ghStorage.getNodes()));
        // MARQ24 MOD END
        LOGGER.info(
                String.format("[%d] Total time: %s.", profileId, TimeUtility.getElapsedTime(startTime, true)));
        LOGGER.info(String.format("[%d] Finished at: %s.", profileId,
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        LOGGER.info("                              ");
    }

    // Make a stamp which help tracking any changes in the size of OSM file.
    File file = new File(osmFile);
    Path pathTimestamp = Paths.get(config.getGraphPath(), "stamp.txt");
    File file2 = pathTimestamp.toFile();
    if (!file2.exists())
        Files.write(pathTimestamp, Long.toString(file.length()).getBytes());

    return gh;
}