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:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

/**
 * Elimina una cancion que entra por parametro
 * @param c//w w w .  ja v  a  2s. c  o m
 * @throws IOException
 */
public void eliminarCancion(Cancion c) throws IOException {

    File arch = new File("./data/canciones/" + c.darArchivo());
    try {
        Files.delete(arch.toPath());
        cant--;
    } catch (IOException e) {
        throw new IOException("No se elimin la cancin: \n" + e.getMessage());
    }

    Comparator<Cancion> comparador = new ComparadorCanciones();
    cancionesXnombre.eliminar(c.darNombre(), c, comparador);
    cancionesXartista.eliminar(c.darArtista(), c, comparador);
    cancionesXid.eliminar(c.toString(), c, comparador);
}

From source file:org.eclipse.ice.item.nuclear.RemoteYamlSyntaxGenerator.java

/**
 * This method generates the YAML and Action syntax files in the local
 * projectSpace/MOOSE directory from a remotely hosted MOOSE-based
 * application.// w w w .  j a v a2  s.com
 *
 * @param monitor
 */
public IStatus generate() {

    // Local Declarations
    IRemoteProcessService processService = null;
    IRemoteProcess yamlRemoteJob = null, syntaxRemoteJob = null;

    // monitor.subTask("Opening the Remote Connection.");
    // monitor.worked(40);

    // Try to open the connection and fail if it will not open
    try {
        connection.open(null);
    } catch (RemoteConnectionException e) {
        // Print diagnostic information and fail
        logger.error(getClass().getName() + " Exception!", e);
        String errorMessage = "Could not create connection to remote machine.";
        return new Status(IStatus.ERROR, "org.eclipse.ice.item.nuclear", 1, errorMessage, null);
    }

    // Do the upload(s) and launch the job if the connection is open
    if (connection.isOpen()) {
        // Diagnostic info
        logger.info("RemoteYamlSyntaxGenerator Message:" + " PTP connection established.");

        // monitor.subTask("Getting a reference to the Process Service on remote machine.");
        // monitor.worked(60);

        // Get the IRemoteProcessService
        processService = connection.getService(IRemoteProcessService.class);

        // Create the process builder for the remote job
        IRemoteProcessBuilder yamlProcessBuilder = processService.getProcessBuilder("sh", "-c",
                appPath + " --yaml");
        IRemoteProcessBuilder syntaxProcessBuilder = processService.getProcessBuilder("sh", "-c",
                appPath + " --syntax");

        // Do not redirect the streams
        yamlProcessBuilder.redirectErrorStream(false);
        syntaxProcessBuilder.redirectErrorStream(false);

        try {
            logger.info("RemoteYamlSyntaxGenerator Message: " + "Attempting to launch with PTP...");
            logger.info("RemoteYamlSyntaxGenerator Message: Command sent to PTP = "
                    + yamlProcessBuilder.command().toString());

            // monitor.subTask("Generating YAML and Action Syntax files on remote machine.");
            // monitor.worked(80);

            yamlRemoteJob = yamlProcessBuilder.start(IRemoteProcessBuilder.FORWARD_X11);
            syntaxRemoteJob = syntaxProcessBuilder.start(IRemoteProcessBuilder.FORWARD_X11);

        } catch (IOException e) {
            // Print diagnostic information and fail
            logger.error(getClass().getName() + " Exception!", e);
            String errorMessage = "Could not execute YAML/Syntax generation on remote machine.";
            return new Status(IStatus.ERROR, "org.eclipse.ice.item.nuclear", 1, errorMessage, null);
        }

        // Monitor the job
        while (!yamlRemoteJob.isCompleted() && !syntaxRemoteJob.isCompleted()) {
            // Give it a second
            try {
                Thread.currentThread();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // Complain
                logger.error(getClass().getName() + " Exception!", e);
            }
        }

        // Get the YAML and Syntax output
        InputStream yamlStream = yamlRemoteJob.getInputStream();
        InputStream syntaxStream = syntaxRemoteJob.getInputStream();

        // Write it to File.
        try {
            String yamlString = IOUtils.toString(yamlStream);
            String syntaxString = IOUtils.toString(syntaxStream);

            // Get the app name
            String animal = Paths.get(appPath).getFileName().toString();

            // Get the path to the Yaml/Syntax files to be created
            // in the MOOSE folder
            Path yamlPath = Paths.get(mooseFolder.getLocation().toOSString() + "/" + animal + ".yaml");
            Path syntaxPath = Paths.get(mooseFolder.getLocation().toOSString() + "/" + animal + ".syntax");

            // Delete existing files
            if (Files.exists(yamlPath)) {
                Files.delete(yamlPath);
            }
            if (Files.exists(syntaxPath)) {
                Files.delete(syntaxPath);
            }

            // monitor.subTask("Writing files locally.");
            // monitor.worked(95);

            // Write the new files.
            Files.write(yamlPath, yamlString.getBytes());
            Files.write(syntaxPath, syntaxString.getBytes());

        } catch (IOException e) {
            logger.error(getClass().getName() + " Exception!", e);
            String errorMessage = "Could not create write files locally.";
            return new Status(IStatus.ERROR, "org.eclipse.ice.item.nuclear", 1, errorMessage, null);
        }

    }

    return Status.OK_STATUS;
}

From source file:org.carcv.impl.core.io.FFMPEGVideoHandlerIT.java

/**
 * Test method for {@link org.carcv.impl.core.io.FFMPEGVideoHandler#generateVideo(java.nio.file.Path, int)}.
 *
 * @throws IOException/*from   w ww .  j av  a 2  s  . c  o m*/
 */
@Test
public void testGenerateVideoPathInt() throws IOException {
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    Path video = new FFMPEGVideoHandler().generateVideo(videoDir, FFMPEGVideoHandler.defaultFrameRate);
    assertTrue("Generated Video file doesn't exist.", Files.exists(video));

    Files.delete(video);
}

From source file:org.apache.tika.parser.BouncyCastleDigestingParserTest.java

@Test
public void testMultipleCombinations() throws Exception {
    Path tmp = Files.createTempFile("tika-digesting-parser-test", "");

    try {//from  ww  w .j ava2  s .  c o  m
        //try some random lengths
        for (int i = 0; i < 10; i++) {
            testMulti(tmp, random.nextInt(100000), random.nextInt(100000), random.nextBoolean());
        }
        //try specific lengths
        testMulti(tmp, 1000, 100000, true);
        testMulti(tmp, 1000, 100000, false);
        testMulti(tmp, 10000, 10001, true);
        testMulti(tmp, 10000, 10001, false);
        testMulti(tmp, 10000, 10000, true);
        testMulti(tmp, 10000, 10000, false);
        testMulti(tmp, 10000, 9999, true);
        testMulti(tmp, 10000, 9999, false);

        testMulti(tmp, 1000, 100, true);
        testMulti(tmp, 1000, 100, false);
        testMulti(tmp, 1000, 10, true);
        testMulti(tmp, 1000, 10, false);
        testMulti(tmp, 1000, 0, true);
        testMulti(tmp, 1000, 0, false);

        testMulti(tmp, 0, 100, true);
        testMulti(tmp, 0, 100, false);

    } finally {
        Files.delete(tmp);
    }
}

From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java

private void checkSnapshotMetadata(Path root) {
    Path metadata = Paths.get(root.toString(), "metadata");
    try {//from  w ww .java 2  s .  c  o m
        Files.walkFileTree(metadata, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path target = Paths.get(root.toString(), "objects",
                        metadata.relativize(file.getParent()).toString());
                if (!Files.exists(target)) {
                    errors.append("-> unexisting target for metadata: ").append(file).append("\r\n");
                    if (fix) {
                        try {
                            Files.delete(file);
                            fixed.append("-> deleted metadata: ").append(file).append("\r\n");
                        } catch (IOException e) {
                            errors.append("-> unable to fix: ").append(e.getMessage()).append("\r\n");
                        }
                    }
                } else if (file.endsWith("ortolang-item-json")) {
                    checkOrtolangItemJson(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

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

        });
    } catch (IOException e) {
        System.out.println("Unable to walk file tree: " + e.getMessage());
    }
}

From source file:org.dishevelled.thumbnail.examples.ThumbnailDrop.java

/**
 * Notify this the specified path has been created.
 *
 * @param path created path/*from  ww w  .j  av a 2s  .  co  m*/
 */
void created(final Path path) {
    logger.trace("heard " + path + " created");

    // sucks
    // String mimeType = Files.probeContentType(path);
    Matcher matcher = JPEG_FILE_EXTENSIONS.matcher(path.toString());
    if (matcher.matches()) {
        try {
            // block until file is non-empty
            waitForNonEmptyFile(path);

            File destinationFile = new File(destinationDirectory.toFile(), fileName(path));
            if (destinationFile.exists()) {
                // if destination file exists, delete newly created path
                logger.info(destinationFile + " exists, deleting " + path);
                Files.delete(path);
            } else {
                // else move newly created path to destination directory
                logger.info("moving " + path + " to " + destinationFile);
                Files.move(path, destinationFile.toPath());
            }

            // trigger thumbnail creation
            logger.trace("creating thumbnails for " + destinationFile);
            thumbnailManager.createThumbnail(destinationFile.toURI(), 0L);
            thumbnailManager.createLargeThumbnail(destinationFile.toURI(), 0L);
        } catch (IOException e) {
            logger.warn("unable to create thumbnails, " + e.getMessage());

            try {
                // delete problematic file from watch directory
                logger.info("deleting " + path);
                Files.delete(path);
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
}

From source file:de.teamgrit.grit.util.config.Configuration.java

/**
 * Writes the content of the String into the config.xml. <b>ATTENTION!</b>
 * the system needs to be rebooted after running this method!
 * /*from w w w.  ja va 2 s.co m*/
 * @param textToWrite
 *            the content for the config.xml file
 * @throws IOException
 *             if the old configuration can not be deleted
 */
public void writeWholeXML(String textToWrite) throws IOException {
    Files.delete(m_configXML.toPath());
    FileUtils.writeStringToFile(m_configXML, textToWrite);
}

From source file:com.clust4j.algo.AffinityPropagationTests.java

@Test
@Override/* w  w w.j a v a 2 s  . c om*/
public void testSerialization() throws IOException, ClassNotFoundException {
    AffinityPropagation ap = new AffinityPropagation(data, new AffinityPropagationParameters().setVerbose(true))
            .fit();

    double[][] a = ap.getAvailabilityMatrix();
    ap.saveObject(new FileOutputStream(TestSuite.tmpSerPath));
    assertTrue(TestSuite.file.exists());

    AffinityPropagation ap2 = (AffinityPropagation) AffinityPropagation
            .loadObject(new FileInputStream(TestSuite.tmpSerPath));
    assertTrue(MatUtils.equalsExactly(a, ap2.getAvailabilityMatrix()));
    assertTrue(ap2.equals(ap));
    Files.delete(TestSuite.path);
}

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

@Override
public void removeFile(File file) throws QueueFileException {
    switch (getFileStatus(file)) {
    case NON_EXISTENT:
        throw new QueueFileException("File or symlink " + file + " no longer exists");
    case CAPTURED_FILE:
    case CAPTURED_SYMLINK:
    case BROKEN_CAPTURED_SYMLINK:
        break;/*from  ww w  . j  a  va 2 s .c om*/
    default:
        throw new QueueFileException("File or symlink " + file + " is not in the queue");
    }

    try {
        Files.delete(file.toPath());
        log.info("File " + file + " deleted from queue area");
    } catch (IOException ex) {
        throw new QueueFileException("File or symlink " + file + " could not be deleted from queue area", ex);
    }
}

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void handleSmallModule(SmallModule moduleDescription, Class clzz, Path uploadersDirectory)
        throws IOException {
    Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Create zip for: {0}", clzz.getName());
    Path outputModulePath = outputDirectory.resolve("sm").resolve(moduleDescription.name() + ".zip");
    Files.createDirectories(outputModulePath.getParent());
    while (Files.exists(outputModulePath)) {
        try {//ww  w .  ja  v  a2 s  .c  o  m
            Files.deleteIfExists(outputModulePath);
        } catch (Exception a) {
            a.printStackTrace();
        }
    }

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    boolean destroyZipIsCorrupt = false;
    URI uri = URI.create("jar:" + outputModulePath.toUri());
    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        smallModuleCreateZip(fs, moduleDescription, clzz, uploadersDirectory);
    } catch (Exception e) {
        e.printStackTrace();
        destroyZipIsCorrupt = true;
    }
    if (destroyZipIsCorrupt) {
        Files.delete(outputModulePath);
    } else {
        String hash = HashUtil.hashFile(outputModulePath.toFile(), index.getHashalgorithm());
        try {
            index.addSmallModule(moduleDescription, hash);
        } catch (Exception a) {
            a.printStackTrace();//ignore
        }
    }
}