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:energy.usef.environment.tool.util.FileUtil.java

public static void removeFolders(String folderName) throws IOException {
    if (folderName == null || folderName.isEmpty() || folderName.trim().equals("\\")
            || folderName.trim().equals("/")) {
        LOGGER.warn("Prevent to delete folders recursively from the root location.");
    } else {//from  w w  w .  j a  v  a2s  .co m
        Path directory = Paths.get(folderName);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                LOGGER.debug("Removing folder " + dir);
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

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

/**
 * This method creates a TeX file from a Submission instance.
 * /*from   w  w  w  .  j  ava 2s  .  com*/
 * @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:maku.mvc.services.ImageService.java

private static boolean delete(String fileName, String path) {
    try {//from w w  w.ja va2  s  .com
        Files.delete(Paths.get(path + "//" + fileName));
        return true;
    } catch (IOException ex) {
        return false;
    }
}

From source file:ch.puzzle.itc.mobiliar.business.utils.SecureFileLoaderTest.java

@After
public void tearDown() throws IOException {
    Files.delete(f);
}

From source file:org.apache.metron.common.cli.ConfigurationManagerIntegrationTest.java

private void cleanDir(File rootDir) throws IOException {
    if (rootDir.isDirectory()) {
        try {/*w w w .j a v  a2 s .co m*/
            Files.delete(Paths.get(rootDir.toURI()));
        } catch (DirectoryNotEmptyException dne) {
            for (File f : rootDir.listFiles()) {
                cleanDir(f);
            }
            rootDir.delete();
        }
    } else {
        rootDir.delete();
    }
}

From source file:com.ibm.watson.app.qaclassifier.ScanLogs.java

public static void getBluemixLogs(String user, String password, String target, String org, String space,
        String app) throws Exception {
    CloudFoundryClient client;/*from w ww .ja  v a  2s.  c o  m*/
    if (user == null || user.isEmpty()) {
        System.out.println("No username/password provided, using saved credentials");
        client = new CloudFoundryClient(new CloudCredentials(new TokensFile().retrieveToken(new URI(target))),
                new URL(target), org, space);
    } else {
        client = new CloudFoundryClient(new CloudCredentials(user, password), new URL(target), org, space);
    }

    client.openFile(app, 0, "logs/" + LOG_FILE, new ClientHttpResponseCallback() {
        @Override
        public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
            Path logDestination = Paths.get(LOG_FILE);
            if (Files.exists(logDestination)) {
                Files.delete(logDestination);
            }
            Files.copy(clientHttpResponse.getBody(), logDestination);
        }
    });
}

From source file:fi.hsl.parkandride.ExportQTypes.java

private static void deleteOldQTypes(Path packageDir) throws IOException {
    Files.walkFileTree(packageDir, new SimpleFileVisitor<Path>() {
        @Override/*from   www  .  j a  v  a  2 s. c  om*/
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
            if (path.getFileName().toString().startsWith(NAME_PREFIX)) {
                Files.delete(path);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:io.crate.testing.Utils.java

public static void deletePath(Path path) throws IOException {
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override//  w w w.j ava  2  s. c om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:org.elasticsearch.qa.die_with_dignity.DieWithDignityIT.java

public void testDieWithDignity() throws Exception {
    // deleting the PID file prevents stopping the cluster from failing since it occurs if and only if the PID file exists
    final Path pidFile = PathUtils.get(System.getProperty("pidfile"));
    final List<String> pidFileLines = Files.readAllLines(pidFile);
    assertThat(pidFileLines, hasSize(1));
    final int pid = Integer.parseInt(pidFileLines.get(0));
    Files.delete(pidFile);
    IOException e = expectThrows(IOException.class,
            () -> client().performRequest(new Request("GET", "/_die_with_dignity")));
    Matcher<IOException> failureMatcher = instanceOf(ConnectionClosedException.class);
    if (Constants.WINDOWS) {
        /*//from   w  ww  . j  a va2 s. c  o  m
         * If the other side closes the connection while we're waiting to fill our buffer
         * we can get IOException with the message below. It seems to only come up on
         * Windows and it *feels* like it could be a ConnectionClosedException but
         * upstream does not consider this a bug:
         * https://issues.apache.org/jira/browse/HTTPASYNC-134
         *
         * So we catch it here and consider it "ok".
        */
        failureMatcher = either(failureMatcher).or(
                hasToString(containsString("An existing connection was forcibly closed by the remote host")));
    }
    assertThat(e, failureMatcher);

    // the Elasticsearch process should die and disappear from the output of jps
    assertBusy(() -> {
        final String jpsPath = PathUtils.get(System.getProperty("runtime.java.home"), "bin/jps").toString();
        final Process process = new ProcessBuilder().command(jpsPath).start();
        assertThat(process.waitFor(), equalTo(0));
        try (InputStream is = process.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line;
            while ((line = in.readLine()) != null) {
                final int currentPid = Integer.parseInt(line.split("\\s+")[0]);
                assertThat(line, pid, not(equalTo(currentPid)));
            }
        }
    });

    // parse the logs and ensure that Elasticsearch died with the expected cause
    final List<String> lines = Files.readAllLines(PathUtils.get(System.getProperty("log")));

    final Iterator<String> it = lines.iterator();

    boolean fatalErrorOnTheNetworkLayer = false;
    boolean fatalErrorInThreadExiting = false;

    while (it.hasNext() && (fatalErrorOnTheNetworkLayer == false || fatalErrorInThreadExiting == false)) {
        final String line = it.next();
        if (line.contains("fatal error on the network layer")) {
            fatalErrorOnTheNetworkLayer = true;
        } else if (line.matches(".*\\[ERROR\\]\\[o.e.b.ElasticsearchUncaughtExceptionHandler\\] \\[node-0\\]"
                + " fatal error in thread \\[Thread-\\d+\\], exiting$")) {
            fatalErrorInThreadExiting = true;
            assertTrue(it.hasNext());
            assertThat(it.next(), equalTo("java.lang.OutOfMemoryError: die with dignity"));
        }
    }

    assertTrue(fatalErrorOnTheNetworkLayer);
    assertTrue(fatalErrorInThreadExiting);
}

From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java

@SneakyThrows
public static void load(Plugin plugin) {
    try { // Check if it is already loaded
        Class.forName("org.yaml.snakeyaml.Yaml");
        return;/* www  .  java2s .co  m*/
    } catch (ClassNotFoundException ignored) {
    }

    Path path = Paths.get("lib", SNAKE_YAML_JAR);

    if (Files.notExists(path)) {
        Files.createDirectories(path.getParent());

        plugin.getLogman().info("Downloading SnakeYAML...");

        URL url = new URL(SNAKE_YAML);
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");

        try (ReadableByteChannel source = Channels.newChannel(new DigestInputStream(url.openStream(), sha1));
                FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE)) {
            out.transferFrom(source, 0, Long.MAX_VALUE);
        }

        if (!new String(Hex.encodeHex(sha1.digest())).equals(EXPECTED_HASH)) {
            Files.delete(path);
            throw new IllegalStateException(
                    "Downloaded SnakeYAML, but checksum check failed. Please try again later.");
        }

        plugin.getLogman().info("Successfully downloaded!");
    }

    loadJAR(path);
}