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:org.thingsboard.server.service.install.sql.SqlDbHelper.java

public static Path dumpTableIfExists(Connection conn, String tableName, String[] columns,
        String[] defaultValues, String dumpPrefix, boolean printHeader) throws Exception {

    if (tableExists(conn, tableName)) {
        Path dumpFile = Files.createTempFile(dumpPrefix, null);
        Files.deleteIfExists(dumpFile);
        CSVFormat csvFormat = CSV_DUMP_FORMAT;
        if (printHeader) {
            csvFormat = csvFormat.withHeader(columns);
        }//from w  ww . j  av a 2 s. com
        try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(dumpFile), csvFormat)) {
            try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM " + tableName)) {
                try (ResultSet tableRes = stmt.executeQuery()) {
                    ResultSetMetaData resMetaData = tableRes.getMetaData();
                    Map<String, Integer> columnIndexMap = new HashMap<>();
                    for (int i = 1; i <= resMetaData.getColumnCount(); i++) {
                        String columnName = resMetaData.getColumnName(i);
                        columnIndexMap.put(columnName.toUpperCase(), i);
                    }
                    while (tableRes.next()) {
                        dumpRow(tableRes, columnIndexMap, columns, defaultValues, csvPrinter);
                    }
                }
            }
        }
        return dumpFile;
    } else {
        return null;
    }
}

From source file:com.fizzed.stork.deploy.DeployHelper.java

static public void deleteRecursively(final Path path) throws IOException {
    if (!Files.exists(path)) {
        return;/*from w w w  . j a va 2  s.  co  m*/
    }

    log.info("Deleting local {}", path);

    Files.walkFileTree(path, 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 ioe) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

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

    Files.deleteIfExists(path);
}

From source file:pl.p.lodz.ftims.server.logic.ChallengeServiceTest.java

@AfterClass
public static void deleteImgDir() throws IOException {
    Stream<Path> stream = Files.list(Paths.get(PHOTOS_DIR));
    stream.forEach((Path p) -> {
        try {/*from   ww  w .  ja  va2 s.c o  m*/
            Files.delete(p);
        } catch (IOException ex) {
            Logger.getLogger(ChallengeServiceTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    Files.deleteIfExists(Paths.get(PHOTOS_DIR));
}

From source file:fr.inria.atlanmod.neoemf.extension.Workspace.java

public File newFile(String prefix) throws IOException {
    Path createdFolder = Files.createTempDirectory(temporaryFolder.toPath(), prefix);
    Files.deleteIfExists(createdFolder);
    return createdFolder.toFile();
}

From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java

public static Path dumpCfIfExists(KeyspaceMetadata ks, Session session, String cfName, String[] columns,
        String[] defaultValues, String dumpPrefix, boolean printHeader) throws Exception {
    if (ks.getTable(cfName) != null) {
        Path dumpFile = Files.createTempFile(dumpPrefix, null);
        Files.deleteIfExists(dumpFile);
        CSVFormat csvFormat = CSV_DUMP_FORMAT;
        if (printHeader) {
            csvFormat = csvFormat.withHeader(columns);
        }//from   w  ww  . j  a  v a2  s .  co m
        try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(dumpFile), csvFormat)) {
            Statement stmt = new SimpleStatement("SELECT * FROM " + cfName);
            stmt.setFetchSize(1000);
            ResultSet rs = session.execute(stmt);
            Iterator<Row> iter = rs.iterator();
            while (iter.hasNext()) {
                Row row = iter.next();
                if (row != null) {
                    dumpRow(row, columns, defaultValues, csvPrinter);
                }
            }
        }
        return dumpFile;
    } else {
        return null;
    }
}

From source file:ru.codemine.ccms.service.DataFileService.java

@Transactional
public void delete(DataFile file) {
    File f = new File(file.getFilename());
    try {//w w  w .j a va 2  s  . c om
        Files.deleteIfExists(f.toPath());
    } catch (IOException ex) {
        log.warn("    ? ?: " + file.getViewName() + "("
                + file.getFilename() + "), : " + ex.getLocalizedMessage());
    }
    dataFileDAO.delete(file);
}

From source file:squash.deployment.lambdas.utils.FileUtils.java

/**
 * GZIPs files in-place.//from w ww.ja  v  a  2 s  . c o  m
 * 
 * <p>Replaces files with their gzip-ed version, without altering the filename. The files can
 *    be a mix of files and folders. Any folders will be recursed into, gzip-ing contained
 *    files in-place. A list of paths to exclude from gzip-ing should also be provided.
 * 
 *    @param pathsToZip the list of paths to gzip.
 *    @param pathsToExclude the list of paths to exclude.
 *    @param logger a CloudwatchLogs logger.
 * @throws IOException 
 */
public static void gzip(List<File> pathsToZip, List<File> pathsToExclude, LambdaLogger logger)
        throws IOException {

    for (File pathToZip : pathsToZip) {
        logger.log("Replacing file with its gzip-ed version: " + pathToZip.getAbsolutePath());
        if (pathsToExclude.contains(pathToZip)) {
            continue;
        }
        if (pathToZip.isDirectory()) {
            logger.log("File is a directory - so recursing...");
            gzip(new ArrayList<File>(Arrays.asList(pathToZip.listFiles())), pathsToExclude, logger);
            continue;
        }

        // File is a file - so gzip it
        File tempZip = File.createTempFile("temp", ".gz", new File(pathToZip.getParent()));
        Files.deleteIfExists(tempZip.toPath());

        byte[] buffer = new byte[1024];
        try {
            try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(tempZip))) {
                try (FileInputStream fileInputStream = new FileInputStream(pathToZip)) {
                    int len;
                    while ((len = fileInputStream.read(buffer)) > 0) {
                        gzipOutputStream.write(buffer, 0, len);
                    }
                }
                gzipOutputStream.finish();
            }
        } catch (IOException e) {
            logger.log("Caught exception whilst zipping file: " + e.getMessage());
            throw e;
        }

        // Replace original file with gzip-ed file, with same name
        Files.copy(tempZip.toPath(), pathToZip.toPath(), StandardCopyOption.REPLACE_EXISTING);
        Files.deleteIfExists(tempZip.toPath());
        logger.log("Replaced file with its gzip-ed version");
    }
}

From source file:wherehows.common.utils.JobsUtilTest.java

@Test
public void testEnvVarResolution() throws IOException, ConfigurationException {
    String propertyStr = "var1=foo\n" + "var2=$JAVA_HOME\n" + "var3=${JAVA_HOME}";

    Path path = createPropertiesFile(propertyStr);

    String fileName = jobNameFromPath(path);
    String dir = path.getParent().toString();

    Properties props = getJobConfigProperties(path.toFile());

    Assert.assertNotEquals(props, null);
    Assert.assertEquals(props.getProperty("var1", ""), "foo");
    Assert.assertTrue(props.getProperty("var2").length() > 0);
    Assert.assertEquals(props.getProperty("var2"), props.getProperty("var3"));
    Files.deleteIfExists(path);
}

From source file:org.openmhealth.data.generator.service.FileSystemDataPointWritingServiceImpl.java

@PostConstruct
public void clearFile() throws IOException {

    if (!append) {
        Files.deleteIfExists(Paths.get(filename));
    }
}

From source file:com.collaide.fileuploader.controllers.LocalFileSynchronizer.java

@Override
public void itemDeleted(ItemDeleted item) {
    try {/*from  ww  w. j a va 2s.c  o m*/
        File fileToDelete = new File(item.getFromPath());
        if (fileToDelete.isDirectory()) {
            FileUtils.deleteDirectory(fileToDelete);
        } else {
            Files.deleteIfExists(new File(item.getFromPath()).toPath());
        }
    } catch (IOException ex) {
        LogManager.getLogger(LocalFileSynchronizer.class).error("cannot delete file file : " + ex);
    }
}