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:algorithm.F5Steganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpPayload = new File("tmp");
    tmpPayload.delete(); // F5 won't override existing files!
    restore("" + tmpPayload.toPath(), "" + carrier.toPath());
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    copiedCarrier.wasCarrier = true;/*from  w w w .ja  v a  2 s .  c om*/
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    FileUtils.copyFile(carrier, copiedCarrier);
    byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpPayload);
    PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
    RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
    FileUtils.writeByteArrayToFile(restoredPayload, payloadSegment.getPayloadBytes());
    restoredPayload.validateChecksum(payloadSegment.getPayloadChecksum());
    restoredPayload.restorationNote = "Payload can be restored correctly.";
    restoredPayload.wasPayload = true;
    restoredPayload.originalFilePath = payloadSegment.getPayloadPath();
    copiedCarrier.originalFilePath = payloadSegment.getCarrierPath();
    restoredFiles.add(restoredPayload);
    FileUtils.forceDelete(tmpPayload);
    restoredFiles.add(copiedCarrier);// carrier can not be restored
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:io.personium.engine.source.FsServiceResourceSourceManager.java

/**
 * Get .pmeta in JSON format./*from  w w w .jav  a2 s  .c om*/
 * @param metaDirPath Directory path in which meta file to be acquired is stored
 * @return .pmeta in JSON format
 * @throws PersoniumEngineException Meta file not found.
 */
private JSONObject getMetaData(String metaDirPath) throws PersoniumEngineException {
    String separator = "";
    if (!metaDirPath.endsWith(File.separator)) {
        separator = File.separator;
    }
    File metaFile = new File(metaDirPath + separator + ".pmeta");
    JSONObject json = null;
    try (Reader reader = Files.newBufferedReader(metaFile.toPath(), Charsets.UTF_8)) {
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(reader);
    } catch (IOException | ParseException e) {
        // IO failure or JSON is broken
        log.info("Meta file not found or invalid (" + this.fsPath + ")");
        throw new PersoniumEngineException("500 Server Error",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR);
    }
    return json;
}

From source file:net.sf.jabref.importer.OpenDatabaseAction.java

/**
 * Load database (bib-file) or, if there exists, a newer autosave version, unless the flag is set to ignore the autosave
 *
 * @param name Name of the bib-file to open
 * @param ignoreAutosave true if autosave version of the file should be ignored
 * @return ParserResult which never is null
 *///from   w w w. j  a  v a 2s. c  om

public static ParserResult loadDatabaseOrAutoSave(String name, boolean ignoreAutosave) {
    // String in OpenDatabaseAction.java
    LOGGER.info("Opening: " + name);
    File file = new File(name);
    if (!file.exists()) {
        ParserResult pr = new ParserResult(null, null, null);
        pr.setFile(file);
        pr.setInvalid(true);
        LOGGER.error(Localization.lang("Error") + ": " + Localization.lang("File not found"));
        return pr;

    }
    try {

        if (!ignoreAutosave) {
            boolean autoSaveFound = AutoSaveManager.newerAutoSaveExists(file);
            if (autoSaveFound) {
                // We have found a newer autosave. Make a note of this, so it can be
                // handled after startup:
                ParserResult postp = new ParserResult(null, null, null);
                postp.setPostponedAutosaveFound(true);
                postp.setFile(file);
                return postp;
            }
        }

        if (!FileBasedLock.waitForFileLock(file.toPath(), 10)) {
            LOGGER.error(Localization.lang("Error opening file") + " '" + name + "'. "
                    + "File is locked by another JabRef instance.");
            return ParserResult.getNullResult();
        }

        Charset encoding = Globals.prefs.getDefaultEncoding();
        ParserResult pr = OpenDatabaseAction.loadDatabase(file, encoding);
        pr.setFile(file);
        if (pr.hasWarnings()) {
            for (String aWarn : pr.warnings()) {
                LOGGER.warn(aWarn);
            }
        }
        return pr;
    } catch (Throwable ex) {
        ParserResult pr = new ParserResult(null, null, null);
        pr.setFile(file);
        pr.setInvalid(true);
        pr.setErrorMessage(ex.getMessage());
        LOGGER.info("Problem opening .bib-file", ex);
        return pr;
    }

}

From source file:com.aspc.cms.module.SyncResourceApp.java

private void registerDir(final WatchService watchService, final File dir) throws Exception {
    // Folder we are going to watch
    Path p = dir.toPath();

    p.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);

    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            registerDir(watchService, f);
        }/*from www.j  a v a2  s .com*/
    }
}

From source file:by.logscanner.LogScanner.java

private void read(File file) throws FileNotFoundException, IOException {
    DataOutputStream out = new DataOutputStream(baos);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

    Stream<String> lines = Files.lines(file.toPath(), StandardCharsets.UTF_8);
    for (String temp : (Iterable<String>) lines::iterator) {
        out.writeUTF((temp.contains(sdf.format(date)) && temp.contains("[" + startupId + "." + requestNo + "]"))
                ? temp + "\n"
                : "");
    }//from  ww w .j  ava2s  .  c o m
}

From source file:com.netflix.genie.agent.cli.ResolveJobSpecCommand.java

@Override
public ExitCode run() {
    log.info("Resolving job specification");

    final ObjectMapper prettyJsonMapper = GenieObjectMapper.getMapper().copy() // Don't reconfigure the shared mapper
            .enable(SerializationFeature.INDENT_OUTPUT);

    final JobSpecification spec;
    final String jobId = resolveJobSpecCommandArguments.getSpecificationId();
    if (!StringUtils.isBlank(jobId)) {
        // Do a specification lookup if an id is given
        log.info("Looking up specification of job {}", jobId);
        try {//from  w  ww.  j a  v a 2 s  .  com
            spec = agentJobService.getJobSpecification(jobId);
        } catch (final JobSpecificationResolutionException e) {
            throw new RuntimeException("Failed to get spec: " + jobId, e);
        }

    } else {
        // Compose a job request from argument
        final AgentJobRequest agentJobRequest;
        try {
            final ArgumentDelegates.JobRequestArguments jobArgs = resolveJobSpecCommandArguments
                    .getJobRequestArguments();
            agentJobRequest = jobRequestConverter.agentJobRequestArgsToDTO(jobArgs);
        } catch (final JobRequestConverter.ConversionException e) {
            throw new RuntimeException("Failed to construct job request from arguments", e);
        }

        // Print request
        if (!resolveJobSpecCommandArguments.isPrintRequestDisabled()) {
            try {
                System.out.println(prettyJsonMapper.writeValueAsString(agentJobRequest));
            } catch (final JsonProcessingException e) {
                throw new RuntimeException("Failed to map request to JSON", e);
            }
        }

        // Resolve via service
        try {
            spec = agentJobService.resolveJobSpecificationDryRun(agentJobRequest);
        } catch (final JobSpecificationResolutionException e) {
            throw new RuntimeException("Failed to resolve job specification", e);
        }
    }

    // Translate response to JSON
    final String specJsonString;
    try {
        specJsonString = prettyJsonMapper.writeValueAsString(spec);
    } catch (final JsonProcessingException e) {
        throw new RuntimeException("Failed to map specification to JSON", e);
    }

    // Print specification
    System.out.println(specJsonString);

    // Write specification to file
    final File outputFile = resolveJobSpecCommandArguments.getOutputFile();
    if (outputFile != null) {
        try {
            Files.write(outputFile.toPath(), specJsonString.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE_NEW);
        } catch (final IOException e) {
            throw new RuntimeException("Failed to write request to: " + outputFile.getAbsolutePath(), e);
        }
    }

    return ExitCode.SUCCESS;
}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public final File renameGrabbedDatafile(File file) throws QueueFileException {
    String extension = FilenameUtils.getExtension(file.toString());
    if (!extension.isEmpty()) {
        extension = "." + extension;
    }//from w w w .  ja  va  2 s . c  o m
    for (int i = 0; i < RETRY; i++) {
        File newFile = generateUniqueFile(extension, false);
        if (!file.renameTo(newFile)) {
            if (!Files.exists(newFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
                throw new QueueFileException("Unable to rename file or symlink " + file + " to " + newFile);
            }
        } else {
            return newFile;
        }
    }
    throw new QueueFileException(RETRY + " attempts to rename file / symlink failed!");
}

From source file:ch.sportchef.business.event.bundary.EventImageResourceTest.java

private byte[] readTestImage() throws IOException {
    final File file = new File(getClass().getClassLoader().getResource(TEST_IMAGE_NAME).getFile());
    return Files.readAllBytes(file.toPath());
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

public static boolean findFiles(ModContainer mod, String base, Function<Path, Boolean> preprocessor,
        BiFunction<Path, Path, Boolean> processor) {
    FileSystem fs = null;//from w w  w. ja  v  a  2  s .  co  m
    try {
        File source = mod.getSource();

        if ("minecraft".equals(mod.getModId()) && DEBUG_LOAD_MINECRAFT) {
            try {
                URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI();
                source = new File(tmp.resolve("..").getPath());
            } catch (URISyntaxException e) {
                FMLLog.log.error("Error finding Minecraft jar: ", e);
                return false;
            }
        }

        Path root = null;
        if (source.isFile()) {
            try {
                fs = FileSystems.newFileSystem(source.toPath(), null);
                root = fs.getPath("/" + base);
            } catch (IOException e) {
                FMLLog.log.error("Error loading FileSystem from jar: ", e);
                return false;
            }
        } else if (source.isDirectory()) {
            root = source.toPath().resolve(base);
        }

        if (root == null || !Files.exists(root))
            return false;

        if (preprocessor != null) {
            Boolean cont = preprocessor.apply(root);
            if (cont == null || !cont.booleanValue())
                return false;
        }

        if (processor != null) {
            Iterator<Path> itr = null;
            try {
                itr = Files.walk(root).iterator();
            } catch (IOException e) {
                FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e);
                return false;
            }

            while (itr != null && itr.hasNext()) {
                Boolean cont = processor.apply(root, itr.next());
                if (cont == null || !cont.booleanValue())
                    return false;
            }
        }

        return true;
    } finally {
        IOUtils.closeQuietly(fs);
    }
}

From source file:com.streamsets.pipeline.stage.destination.recordstolocalfilesystem.RecordsToLocalFileSystemTarget.java

private void rotate(boolean createNewFile) throws IOException {
    OutputStream outputStream = null;
    try {/*from  w  ww . j  a v  a2 s .c  o m*/
        IOUtils.closeQuietly(generator);
        generator = null;
        if (activeFile.exists()) {
            File finalName = findFinalName();
            LOG.debug("Rotating '{}' to '{}'", activeFile, finalName);
            Files.move(activeFile.toPath(), finalName.toPath());
        }
        if (createNewFile) {
            LOG.debug("Creating new '{}'", activeFile);
            outputStream = new FileOutputStream(activeFile);
            if (maxFileSizeBytes > 0) {
                countingOutputStream = new CountingOutputStream(outputStream);
                outputStream = countingOutputStream;
            }
            generator = generatorFactory.getGenerator(outputStream);
        }
        lastRotation = System.currentTimeMillis();
    } catch (IOException ex) {
        IOUtils.closeQuietly(generator);
        generator = null;
        IOUtils.closeQuietly(countingOutputStream);
        countingOutputStream = null;
        IOUtils.closeQuietly(outputStream);
        throw ex;
    }
}