Example usage for java.nio.file Files delete

List of usage examples for java.nio.file Files delete

Introduction

In this page you can find the example usage for java.nio.file Files delete.

Prototype

public static void delete(Path path) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:org.auscope.portal.server.web.service.TemplateLintService.java

private List<LintResult> pylint(String template) throws PortalServiceException {
    List<LintResult> lints = new ArrayList<LintResult>();

    // Save template as a temporary python file
    Path f;/* w  w w.j  ava  2s.c  o m*/
    try {
        f = Files.createTempFile("contemplate", ".py");
        BufferedWriter writer = Files.newBufferedWriter(f);
        writer.write(template);
        writer.close();
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to write template to temporary file.", ex);
    }

    // Run pylint in the temp file's directory
    String results;
    String errors;
    ArrayList<String> cmd = new ArrayList<String>(this.pylintCommand);
    cmd.add(f.getFileName().toString());
    try {
        ProcessBuilder pb = new ProcessBuilder(cmd).directory(f.getParent().toFile());

        // Start the process, and consume the results immediately so Windows is happy.
        Process p = pb.start();
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        results = stdout.lines().collect(Collectors.joining("\n"));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        errors = stderr.lines().collect(Collectors.joining("\n"));

        if (!p.waitFor(DEFAULT_TIMEOUT, TimeUnit.SECONDS)) {
            // Timed out
            throw new PortalServiceException(String.format(
                    "pylint process failed to complete before {} second timeout elapsed", DEFAULT_TIMEOUT));
        }

        // Finished successfully? pylint returns 0 on success *with no
        // issues*, 1 on failure to run properly, 2/4/8/16 for successful
        // completion with python convention/refactor/warning/error (codes
        // 2-16 bit-ORd into final result) or 32 on usage error.
        int rv = p.exitValue();
        if (rv == 1 || rv == 32) {
            logger.error("pylint failed");
            logger.debug("\npylint stderr:\n" + errors);
            logger.debug("\npylint stdout:\n" + results);
            throw new PortalServiceException(
                    String.format("pylint process returned non-zero exit value: {}", rv));
        } else if (rv != 0) {
            logger.info("pylint found issues");
        }
    } catch (PortalServiceException pse) {
        throw pse;
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to run pylint on template", ex);
    }

    // Parse results into LintResult objects
    lints = parsePylintResults(results);

    // Clean up
    try {
        Files.delete(f);
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to delete temporary template file.", ex);
    }

    return lints;
}

From source file:net.pms.util.FilePermissionsTest.java

@Test
public void testFilePermissions() throws URISyntaxException, IOException {
    FilePermissions permissions = new FilePermissions(new File(""));
    assertTrue("CurrentFolderIsFolder", permissions.isFolder());
    assertTrue("CurrentFolderIsReadable", permissions.isReadable());
    assertTrue("CurrentFolderIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(Paths.get("").toAbsolutePath());
    assertTrue("CurrentFolderIsFolder", permissions.isFolder());
    assertTrue("CurrentFolderIsReadable", permissions.isReadable());
    assertTrue("CurrentFolderIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(FileUtils.toFile(CLASS.getResource("english-utf8-with-bom.srt")));
    assertTrue("FileIsReadable", permissions.isReadable());
    assertTrue("FileIsWritable", permissions.isWritable());
    assertFalse("FileIsNotFolder", permissions.isFolder());
    assertFalse("FileIsNotBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(permissions.getFile().getParentFile());
    assertTrue("ParentIsFolder", permissions.isFolder());
    assertTrue("ParentIsBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(Paths.get(CLASS.getResource("english-utf8-with-bom.srt").toURI()));
    assertTrue("FileIsReadable", permissions.isReadable());
    assertTrue("FileIsWritable", permissions.isWritable());
    assertFalse("FileIsNotFolder", permissions.isFolder());
    assertFalse("FileIsNotBrowsable", permissions.isBrowsable());

    permissions = new FilePermissions(permissions.getPath().getParent());
    assertTrue("ParentIsFolder", permissions.isFolder());
    assertTrue("ParentIsBrowsable", permissions.isBrowsable());

    File file = new File(System.getProperty("java.io.tmpdir"),
            String.format("UMS_temp_writable_file_%d.tmp", new Random().nextInt(10000)));
    if (file.createNewFile()) {
        try {/*from   ww w .  ja  va  2 s .  c o m*/
            assertTrue("TempFileIsReadable", new FilePermissions(file).isReadable());
            assertTrue("TempFileIsWritable", new FilePermissions(file).isWritable());
            assertFalse("TempFileIsNotFolder", new FilePermissions(file).isFolder());
            assertFalse("TempFileIsNotBrowsable", new FilePermissions(file).isBrowsable());
        } finally {
            file.delete();
        }
    }

    Path path = Paths.get(System.getProperty("java.io.tmpdir"),
            String.format("UMS_temp_writable_file_%d.tmp", new Random().nextInt(10000)));
    Files.createFile(path);
    try {
        assertTrue("TempFileIsReadable", new FilePermissions(path).isReadable());
        assertTrue("TempFileIsWritable", new FilePermissions(path).isWritable());
        assertFalse("TempFileIsNotFolder", new FilePermissions(path).isFolder());
        assertFalse("TempFileIsNotBrowsable", new FilePermissions(path).isBrowsable());
    } finally {
        Files.delete(path);
    }
}

From source file:junit.org.rapidpm.microdao.HsqlDBBaseTestUtils.java

private boolean deleteDirectory(final String path) {
    final File indexDirectory = new File(path);
    if (indexDirectory.exists()) {
        try {/*from   w w  w  .j  a  v a2  s .com*/
            Files.walkFileTree(indexDirectory.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                        throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    return false;
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void closeAndSaveBundleNotDelete() throws Exception {
    Path path = Files.createTempFile("bundle", ".zip");
    Bundle bundle = Bundles.createBundle(path);
    Path destination = Files.createTempFile("test", ".zip");
    destination.toFile().deleteOnExit();
    Files.delete(destination);
    assertFalse(Files.exists(destination));
    Bundles.closeAndSaveBundle(bundle, destination);
    assertTrue(Files.exists(destination));
    assertTrue(Files.exists(bundle.getSource()));
}

From source file:com.codenvy.api.audit.server.AuditReportPrinterTest.java

@AfterMethod
public void tearDown() throws Exception {
    Files.delete(auditReport);
}

From source file:org.roda_project.commons_ip.model.impl.hungarian.HungarianSIP.java

private Path getZipPath(Path destinationDirectory, String fileNameWithoutExtension) throws IPException {
    Path zipPath;/*from w  ww  .  j  a  v a2s  . c  o  m*/
    if (fileNameWithoutExtension != null) {
        zipPath = destinationDirectory.resolve(fileNameWithoutExtension + SIP_FILE_EXTENSION);
    } else {
        zipPath = destinationDirectory.resolve(getId() + SIP_FILE_EXTENSION);
    }

    try {
        if (Files.exists(zipPath)) {
            Files.delete(zipPath);
        }
    } catch (IOException e) {
        throw new IPException("Error deleting already existing ZIP", e);
    }

    return zipPath;
}

From source file:net.sf.jabref.logic.exporter.FileSaveSession.java

@Override
public void cancel() {
    try {//from w  w w.j a  v a 2  s. c  o m
        Files.delete(temporaryFile);
    } catch (IOException e) {
        LOGGER.warn("Cannot delete temporary file", e);
    }
}

From source file:org.apache.tika.server.CXFTestBase.java

protected String readArchiveText(InputStream inputStream) throws IOException {
    Path tempFile = writeTemporaryArchiveFile(inputStream, "zip");
    ZipFile zip = new ZipFile(tempFile.toFile());
    zip.getEntry(UnpackerResource.TEXT_FILENAME);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(zip.getInputStream(zip.getEntry(UnpackerResource.TEXT_FILENAME)), bos);

    zip.close();//from ww w.  j a v a  2s .  c o  m
    Files.delete(tempFile);
    return bos.toString(UTF_8.name());
}

From source file:nl.mpi.oai.harvester.control.FileSynchronization.java

/**
 *   Removes temporary directory and renames to original name
 *//* w w  w .jav a2 s.com*/
private static void deleteDirectory(final String dir, final Provider provider) {
    File[] files = new File(dir).listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isFile()) {
                Path path = Paths.get(dir + "/" + f.getName());
                try {
                    Files.delete(path);
                    saveToHistoryFile(provider, path, Operation.DELETE);
                } catch (IOException e) {
                    logger.error("Unable to delete File " + path + ": ", e);
                }
            }
        }
    }
    try {
        Path directory = Paths.get(dir);
        Files.delete(directory);
        File toRename = new File(dir + "_new");
        toRename.renameTo(new File(dir));
    } catch (IOException e) {
        logger.error("Unable to delete directory : ", e);
    }
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private void registerCleanup() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*from  w  ww . jav a 2  s  . c  o  m*/
        public void run() {
            if (logger.isDebugEnabled()) {
                logger.debug("[UNSIGN] shutting down unsign jar command");
            }
            if (tempDir != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[UNSIGN] tempDir is not null");
                }
                try {
                    Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                throws IOException {
                            if (logger.isDebugEnabled()) {
                                logger.debug("[UNSIGN] deleting file={}", file.getFileName());
                            }
                            Files.delete(file);
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                throws IOException {
                            if (exc == null) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("[UNSIGN] deleting dir={}", dir.getFileName());
                                }
                                Files.delete(dir);
                                return FileVisitResult.CONTINUE;
                            } else {
                                // directory iteration failed
                                throw exc;
                            }
                        }
                    });
                } catch (Exception exc) {
                    logger.error("error removing tempDir=" + tempDir, exc);
                }
            }
        }
    });
}