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:Main.java

/**
 * Saves the object to the file.//www  .j  av  a 2 s. co m
 *
 * @param <T> the object type.
 * @param path the XML file.
 * @param object the object to be saved.
 */
public static <T> void saveObject(Path path, T object) {

    if (path == null || object == null) {
        throw new RuntimeException("The path to file or object is null!");
    }

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(object, path.toFile());
    } catch (Exception ex) {
        throw new RuntimeException("Error saving the object to path " + path.toString(), ex);
    }
}

From source file:com.chigix.autosftp.Application.java

public static void watchDir(Path dir) throws Exception {
    // The monitor will perform polling on the folder every 5 seconds
    final long pollingInterval = 5 * 1000;

    File folder = dir.toFile();

    if (!folder.exists()) {
        // Test to see if monitored folder exists
        throw new FileNotFoundException("Directory not found: " + dir);
    }//from w w  w. j  a  va  2s .  c om

    FileAlterationObserver observer = new FileAlterationObserver(folder);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {
        // Is triggered when a file is created in the monitored folder
        @Override
        public void onFileCreate(File file) {
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File created: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            ArrayList<String> lackDirs = new ArrayList<>();
            String tmpParentPath = destPath;
            while (!tmpParentPath.equals("/") && !tmpParentPath.equals("\\")) {
                tmpParentPath = new File(tmpParentPath).getParentFile().toPath().toString().replace('\\', '/');
                try {
                    sftpChannel.cd(tmpParentPath);
                } catch (SftpException ex) {
                    if (ex.id == SSH_FX_NO_SUCH_FILE) {
                        lackDirs.add(tmpParentPath);
                        continue;
                    }
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    return;
                }
                break;
            }
            for (int i = lackDirs.size() - 1; i > -1; i--) {
                try {
                    sftpChannel.mkdir(lackDirs.get(i));
                } catch (SftpException ex) {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    System.err.println(destPath + " Creating Fail.");
                    return;
                }
            }
            InputStream fi = null;
            try {
                fi = new FileInputStream(file);
                sftpChannel.put(fi, destPath, 644);
            } catch (FileNotFoundException ex) {
                System.out.println("File: " + file.getAbsolutePath() + " not exists.");
                return;
            } catch (SftpException ex) {
                Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                return;
            } finally {
                if (fi != null) {
                    try {
                        fi.close();
                    } catch (IOException ex) {
                    }
                }
            }
            System.out.println("File Uploaded: " + destPath);
        }

        // Is triggered when a file is deleted from the monitored folder
        @Override
        public void onFileDelete(File file) {
            if (file.exists()) {
                return;
            }
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File Deleted: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            try {
                sftpChannel.rm(destPath);
            } catch (SftpException ex) {
                if (ex.id == SSH_FX_NO_SUCH_FILE) {
                } else {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            System.out.println("Remote Deleted: " + relativePath);
        }

        @Override
        public void onFileChange(File file) {
            this.onFileCreate(file);
        }

    };

    observer.addListener(listener);
    monitor.addObserver(observer);
    monitor.start();
}

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  ww w  . j  a  v a2s  .  com
    Assert.isTrue(Files.isWritable(dir.toPath()), "Cannot write to directory:" + path);
    return path;
}

From source file:de.teamgrit.grit.report.TexGenerator.java

/**
 * This method creates a TeX file from a Submission instance.
 * /*www .java 2  s.  c o  m*/
 * @param submission
 *            A SubmissionObj containing the information that the content
 *            gets generated from.
 * @param outdir
 *            the output directory
 * @param courseName
 *            the name of the course the exercise belongs to
 * @param exerciseName
 *            the name of the exercise
 * @return The Path to the created TeX file.
 * @throws IOException
 *             If something goes wrong when writing.
 */
public static Path generateTex(final Submission submission, final Path outdir, final String courseName,
        final String exerciseName) throws IOException {

    final File location = outdir.toFile();

    File file = new File(location, submission.getStudent().getName() + ".report.tex");
    if (Files.exists(file.toPath())) {
        Files.delete(file.toPath());
    }
    file.createNewFile();

    writePreamble(file);
    writeHeader(file, submission, courseName, exerciseName);
    writeOverview(file, submission);
    writeTestResult(file, submission);

    // if there are compile errors, put these in the .tex file instead of
    // JUnit Test result
    CheckingResult checkingResult = submission.getCheckingResult();
    if (!(checkingResult.getCompilerOutput().isCleanCompile())) {
        writeCompilerErrors(file, submission);
    } else {
        TestOutput testResults = checkingResult.getTestResults();
        if ((testResults.getPassedTestCount() < testResults.getTestCount()) && testResults.getDidTest()) {
            writeFailedTests(file, submission);
        }
    }

    writeCompilerOutput(file, submission);
    writeSourceCode(file, submission);
    writeClosing(file);

    return file.toPath();
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Deletes a file. //from w ww .ja va  2s  . com
 * 
 * @param file the path to the file 
 * @return boolean 
 * @throws IOException if an I/O error occurs
 * @throws IllegalArgumentException if file is null
 */
public static boolean deleteFile(Path file) throws IOException {
    if ((file == null))
        throw new IllegalArgumentException("file cannot be null");
    try {
        if (file.toFile().canWrite()) {
            Files.delete(file);
        }
        return !Files.exists(file, LinkOption.NOFOLLOW_LINKS);
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("An IO exception occured while deleting file '" + file + "' with error:"
                + e.getLocalizedMessage());
    }
}

From source file:de.teamgrit.grit.report.PdfConcatenator.java

/**
 * Concatinates pdfs generated {@link TexGenerator}.
 *
 * @param folderWithPdfs//from w  w  w .j ava2 s.  c  o  m
 *            the folder with pdfs
 * @param outPath
 *            the out path
 * @param exerciseName
 *            the context
 * @param studentsWithoutSubmissions
 *            list of students who did not submit any solution
 * @return the path to the created PDF
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected static Path concatPDFS(Path folderWithPdfs, Path outPath, String exerciseName,
        List<Student> studentsWithoutSubmissions) throws IOException {

    if ((folderWithPdfs == null) || !Files.isDirectory(folderWithPdfs)) {
        throw new IOException("The Path doesn't point to a Folder");
    }

    File file = new File(outPath.toFile(), "report.tex");

    if (Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        Files.delete(file.toPath());
    }
    file.createNewFile();

    writePreamble(file, exerciseName);
    writeMissingStudents(file, studentsWithoutSubmissions);
    writeFiles(file, folderWithPdfs);
    writeClosing(file);

    PdfCreator.createPdfFromPath(file.toPath(), outPath);

    return file.toPath();

}

From source file:org.apache.coheigea.bigdata.knox.ranger.KnoxRangerTest.java

public static void setupLdap() throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//w  w w . j  a  v a 2 s .c o  m
    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
    ldapTransport = new TcpTransport(0);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport);
    ldap.start();
}

From source file:com.bbva.kltt.apirest.core.web.Utilities.java

/**
 * Read the file content/*from  w  w  w  .  ja  v  a 2 s  .  c o  m*/
 * @param filePath with the file path
 * @return the file content as byte array
 * @throws APIRestGeneratorException with an occurred exception
 */
public static byte[] readFileContent(final String filePath) throws APIRestGeneratorException {
    Path path = null;

    if (filePath.toLowerCase().startsWith(ConstantsInput.SO_PATH_STRING_PREFIX)) {
        path = Paths.get(URI.create(filePath));
    } else {
        path = Paths.get(filePath, new String[0]);
    }

    byte[] fileContent = null;

    if (Files.exists(path, new LinkOption[0])) {
        try {
            fileContent = FileUtils.readFileToByteArray(path.toFile());
        } catch (IOException ioException) {
            final String errorString = "IOException when reading the file '" + filePath + "': " + ioException;

            Utilities.LOGGER.error(errorString, ioException);
            throw new APIRestGeneratorException(errorString, ioException);
        }
    }

    return fileContent;
}

From source file:objective.taskboard.it.TemplateIT.java

private static File corruptedFile() throws IOException, URISyntaxException {
    Path temp = Files.createTempFile("Followup", ".xlsm");
    ZipUtils.zip(ZipUtils.stream(okTemplate()).map(ze -> {
        if (StringUtils.endsWith(ze.getName(), "workbook.xml.rels"))
            ze.setInputStream(TemplateIT.class.getResourceAsStream("/objective/taskboard/utils/file.xml"));
        return ze;
    }), temp);/*from  w w  w .j  a  v a 2 s  .com*/
    return temp.toFile();
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

private static void unpack(File archive, File destionation) throws IOException {
    try (ZipFile zip = new ZipFile(archive)) {
        Map<File, String> symLinks = new LinkedHashMap<>();
        Enumeration<ZipArchiveEntry> iterator = zip.getEntries();
        // Top directory name we are going to ignore
        String parentDirectory = iterator.nextElement().getName();
        // Iterate files & folders
        while (iterator.hasMoreElements()) {
            ZipArchiveEntry entry = iterator.nextElement();
            String name = entry.getName().substring(parentDirectory.length());
            File outputFile = new File(destionation, name);
            if (name.startsWith("interactive_ui_tests")) {
                continue;
            }//  w  ww  . ja va2 s. c  om
            if (entry.isUnixSymlink()) {
                symLinks.put(outputFile, zip.getUnixSymlink(entry));
            } else if (!entry.isDirectory()) {
                if (!outputFile.getParentFile().isDirectory()) {
                    outputFile.getParentFile().mkdirs();
                }
                try (FileOutputStream outStream = new FileOutputStream(outputFile)) {
                    IOUtils.copy(zip.getInputStream(entry), outStream);
                }
            }
            // Set permission
            if (!entry.isUnixSymlink() && outputFile.exists())
                try {
                    Files.setPosixFilePermissions(outputFile.toPath(),
                            modeToPosixPermissions(entry.getUnixMode()));
                } catch (Exception e) {
                    // ignore
                }
        }
        for (Map.Entry<File, String> entry : symLinks.entrySet()) {
            try {
                Path source = Paths.get(entry.getKey().getAbsolutePath());
                Path target = source.getParent().resolve(entry.getValue());
                if (!source.toFile().exists())
                    Files.createSymbolicLink(source, target);
            } catch (Exception e) {
                // ignore
            }
        }
    }
}