Example usage for java.nio.file Files deleteIfExists

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

Introduction

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

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:kmi.taa.core.Crawler.java

public void run(String triplesFile, String dirOutput, String service, String proxy)
        throws ClientProtocolException, IOException, URISyntaxException {
    TreeMap<Integer, String> map = new TreeMap<>();
    map = readSourceTriples(triplesFile);
    log.info("Crawling subject links...");
    String file = dirOutput + "subjectlinks.txt";
    Files.deleteIfExists(Paths.get(dirOutput + "subjectlinks.txt"));
    crawlAll(map, service, proxy, file);
    log.info("Crawling subject links completed. ");

}

From source file:ingest.inspect.GeoTiffInspector.java

@Override
public DataResource inspect(DataResource dataResource, boolean host) throws DataInspectException,
        AmazonClientException, InvalidInputException, IOException, FactoryException {
    // Gather GeoTIFF relevant metadata
    String fileName = String.format("%s%s%s.%s", DATA_TEMP_PATH, File.separator, dataResource.getDataId(),
            "tif");

    logger.log(// ww w  .  ja v  a  2 s .c  o  m
            String.format("Begin GeoTools Parsing for %s at temporary file %s", dataResource.getDataId(),
                    fileName),
            Severity.INFORMATIONAL, new AuditElement(INGEST, "beginParsingGeoTiff", fileName));

    File geoTiffFile = new File(fileName);
    GridCoverage2DReader reader = getGridCoverage(dataResource, geoTiffFile);
    GridCoverage2D coverage = (GridCoverage2D) reader.read(null);
    CoordinateReferenceSystem coordinateReferenceSystem = coverage.getCoordinateReferenceSystem();
    double[] upperRightCorner = coverage.getEnvelope().getUpperCorner().getDirectPosition().getCoordinate();
    double[] lowerLeftCorner = coverage.getEnvelope().getLowerCorner().getDirectPosition().getCoordinate();

    // Set the Metadata
    SpatialMetadata spatialMetadata = new SpatialMetadata();
    spatialMetadata.setMinX(lowerLeftCorner[0]);
    spatialMetadata.setMinY(lowerLeftCorner[1]);
    spatialMetadata.setMaxX(upperRightCorner[0]);
    spatialMetadata.setMaxY(upperRightCorner[1]);

    // Get the SRS and EPSG codes
    spatialMetadata.setCoordinateReferenceSystem(coordinateReferenceSystem.toWKT());
    spatialMetadata.setEpsgCode(CRS.lookupEpsgCode(coordinateReferenceSystem, true));

    // Set the Spatial Metadata
    dataResource.spatialMetadata = spatialMetadata;

    // Populate the projected EPSG:4326 spatial metadata
    try {
        dataResource.spatialMetadata
                .setProjectedSpatialMetadata(ingestUtilities.getProjectedSpatialMetadata(spatialMetadata));
    } catch (Exception exception) {
        String error = String.format(
                "Could not project the spatial metadata for Data %s because of exception: %s",
                dataResource.getDataId(), exception.getMessage());
        LOG.error(error, exception);
        logger.log(error, Severity.WARNING);
    }

    // Delete the file; cleanup.
    try {
        // Required to release the lock on the File for deletion
        PlanarImage planarImage = (PlanarImage) coverage.getRenderedImage();
        ImageUtilities.disposePlanarImageChain(planarImage);
        // Dispose reader and coverage
        reader.dispose();
        coverage.dispose(true);
        // Finally, delete the file.
        Files.deleteIfExists(geoTiffFile.toPath());
    } catch (Exception exception) {
        String error = String.format("Error cleaning up GeoTiff file for %s Load: %s", dataResource.getDataId(),
                exception.getMessage());
        LOG.error(error, exception, new AuditElement(INGEST, "failedToDeleteTemporaryGeoTiff", fileName));
        logger.log(error, Severity.WARNING);
    }

    logger.log(
            String.format("Completed GeoTools Parsing for %s at temporary file %s", dataResource.getDataId(),
                    fileName),
            Severity.INFORMATIONAL, new AuditElement(INGEST, "completeParsingGeoTiff", fileName));

    // Return the metadata
    return dataResource;
}

From source file:Main.StaticTools.java

private static void removeFiles(File file) {
    File[] directories = file.listFiles((File dir, String name) -> dir.isDirectory());
    for (File dir1 : directories) {
        if (dir1.isDirectory()) {
            File[] content = dir1.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    name = name.toLowerCase();
                    return name.endsWith("__highres.jpg");
                }// w  ww. ja  v  a  2 s . c om
            });
            if (content.length > 0) {
                for (int i = 0; i < content.length; i++) {
                    String absolutePath = content[i].getAbsolutePath();
                    try {
                        Files.deleteIfExists(
                                Paths.get(absolutePath.substring(0, absolutePath.length() - 13) + ".jpg"));
                    } catch (IOException e) {
                        errorOut(content[i].getName(), e);
                    }
                }
            }
        }
    }

}

From source file:com.arpnetworking.configuration.jackson.JsonNodeDirectorySourceTest.java

private static void deleteDirectory(final File directory) throws IOException {
    if (directory.exists() && directory.isDirectory()) {
        for (final File file : MoreObjects.firstNonNull(directory.listFiles(), new File[0])) {
            Files.deleteIfExists(file.toPath());
        }//from   w w  w.ja  va 2  s. c o  m
    }
    Files.deleteIfExists(directory.toPath());
}

From source file:org.ballerinalang.test.auth.AuthorizationTest.java

@AfterClass
public void tearDown() throws IOException {
    Files.deleteIfExists(ballerinaConfCopyPath);
}

From source file:org.corehunter.tests.data.simple.SimpleDistanceMatrixDataTest.java

@Test
public void toCsvFile() throws IOException {
    dataName = "out.csv";
    expectedHeaders = HEADERS_UNIQUE_NAMES;

    SimpleDistanceMatrixData distanceData = new SimpleDistanceMatrixData(expectedHeaders, DISTANCES);

    Path path = Paths.get(TEST_OUTPUT);

    Files.createDirectories(path);

    path = Files.createTempDirectory(path, "DistanceMatrix-Csv");

    path = Paths.get(path.toString(), dataName);

    Files.deleteIfExists(path);

    System.out.println(" |- Write distance File " + dataName);
    distanceData.writeData(path, FileType.CSV);

    testData(SimpleDistanceMatrixData.readData(path, FileType.CSV));
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUserNoController() {
    if (!isValidData()) {
        return;/*www  .j ava 2  s  . co  m*/
    }
    tfUsername.setEditable(false);
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    User objUser;
    if (mAvatar != null) {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if ((new ModelUser()).editItem(objUser)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    mUser = objUser;
    this.dispose();
}

From source file:com.qwazr.extractor.parser.ImageParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {
    final Path tempFile = ParserAbstract.createTempFile(inputStream,
            extension == null ? "image" : "." + extension);
    try {//w  w w.ja  va2 s.  c  o m
        parseContent(parameters, tempFile, extension, mimeType, resultBuilder);
    } finally {
        Files.deleteIfExists(tempFile);
    }
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;/*w  ww .ja  v  a  2s.  co  m*/
    try {
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.kitodo.filemanagement.FileManagement.java

@Override
public boolean delete(URI uri) throws IOException {
    if (Objects.isNull(uri) || uri.getPath().isEmpty()) {
        /*//from  w ww.j  a  v a2 s.  co  m
        This exception is thrown when the passed URI is empty or null.
        Using this URI would cause the deletion of the metadata directory.
        */
        throw new IOException("Attempt to delete subdirectory with URI that is empty or null!");
    }
    uri = fileMapper.mapUriToKitodoDataDirectoryUri(uri);
    File file = new File(uri);
    if (file.exists()) {
        if (file.isFile()) {
            return Files.deleteIfExists(file.toPath());
        }
        if (file.isDirectory()) {
            FileUtils.deleteDirectory(file);
            return true;
        }
        return false;
    }
    return true;
}