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:fr.duminy.jbackup.core.ConfigurationManagerTest.java

@Test
public void testInit_nonExistingDirectory() throws Exception {
    Path dir = tempFolder.newFolder().toPath();
    Files.delete(dir);
    assertThat(Files.exists(dir)).as("directory exists").isFalse();

    new ConfigurationManager(dir);

    assertThat(Files.exists(dir)).as("directory exists").isTrue();
}

From source file:org.objectspace.rfid.feig.FeigRFID.java

/**
 * initializes the reader to deal with BRM or ISO tags needs optional
 * configuration value * device.feig.storeconfigfile *
 * device.feig.configfile (name of firmware configuration)
 * /*from  w  ww  .  j ava2  s .co m*/
 * @throws Exception
 */
public void init() throws Exception {
    String storeConfigFile = config.getString("device.feig.storeconfigfile", null);
    if (storeConfigFile != null) {
        if (Files.isRegularFile(Paths.get(storeConfigFile))) {
            Files.delete(Paths.get(storeConfigFile));
        }
        System.out.println("Storing actual configuration to " + storeConfigFile);
        copyConfigToFile(storeConfigFile);
    }
    String readerConfigFile = config.getString("device.feig.configfile", null);
    if (readerConfigFile != null) {
        if (!Files.isRegularFile(Paths.get(readerConfigFile))) {
            throw new Exception("configfile " + readerConfigFile + " not a regular file");
        }
        System.out.println("Loading configuration file: " + readerConfigFile);
        copyFileToConfig(readerConfigFile);
    }

    reader.setTableSize(FedmIscReaderConst.ISO_TABLE, 17496);
    reader.setTableSize(FedmIscReaderConst.BRM_TABLE, 1104);
}

From source file:org.syncany.plugins.flickr.FlickrTransferManager.java

private String createNewAlbum() throws StorageException {
    try {/*from   w w w  .  j a v a2 s  .c o m*/
        // Create and upload dummy file (album needs at least one photo)
        Path dummyFileTempPath = Files.createTempFile("syncany-temp", ".tmp");
        Files.write(dummyFileTempPath, "Syncany rocks!".getBytes());

        String dummyPhotoId = upload(dummyFileTempPath.toFile(),
                new TempRemoteFile(new MultichunkRemoteFile(MultiChunkId.secureRandomMultiChunkId())), false);

        Files.delete(dummyFileTempPath);

        // Create album              
        String title = "Syncany " + (1000 + Math.abs(new Random().nextInt(8999)));
        String description = "Flickr-based Syncany repository. Details at www.syncany.org!";

        Photoset photoset = flickr.getPhotosetsInterface().create(title, description, dummyPhotoId);
        return photoset.getId();
    } catch (Exception e) {
        throw new StorageException("Cannot initialize repository. Creating Flickr album failed.", e);
    }
}

From source file:com.github.ffremont.microservices.springboot.node.services.MsService.java

/**
 * Retourne le flux  lire//from  w  w  w . j  a v a 2 s. c om
 *
 * @param msName
 * @return
 */
public Path getBinary(String msName) {
    MicroServiceRest ms = this.getMs(msName);

    if (ms == null) {
        return null;
    }

    MasterUrlBuilder builder = new MasterUrlBuilder(cluster, node, masterhost, masterPort, masterCR);
    builder.setUri(msName + "/binary");

    Path tempFileBinary = null;
    try {
        tempFileBinary = Files.createTempFile("node", "jarBinary");
        HttpURLConnection managerConnection = (HttpURLConnection) (new URL(builder.build())).openConnection();
        managerConnection.setRequestProperty("Authorization", "Basic "
                .concat(new String(Base64.getEncoder().encode((username + ":" + password).getBytes()))));
        managerConnection.setRequestProperty("Accept", "application/java-archive");
        managerConnection.connect();

        if (managerConnection.getResponseCode() != 200) {
            LOG.warn("Manager : rcupration impossible, statut {}", managerConnection.getResponseCode());
            return tempFileBinary;
        }

        FileOutputStream fos = new FileOutputStream(tempFileBinary.toFile());
        try (InputStream is = managerConnection.getInputStream()) {
            byte[] buffer = new byte[10240]; // 10ko
            int read;
            while (-1 != (read = is.read(buffer))) {
                fos.write(buffer, 0, read);
            }
            fos.flush();
            is.close();
        }
    } catch (IOException ex) {
        LOG.error("Impossible de rcuprer le binaire", ex);
        if (tempFileBinary != null) {
            try {
                Files.delete(tempFileBinary);
            } catch (IOException e) {
            }
        }
    }

    return tempFileBinary;
}

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

@Test
public void testIsFileLocatedInDirectorySymbolicLinkNok() throws IOException {
    //symlinks work only on unix
    Assume.assumeTrue(isUnix());/*from ww w. ja va  2  s . co m*/
    Path f2 = Paths.get(FileUtils.getTempDirectoryPath(), "test.txt");
    Files.createFile(f2);

    Path symlink = Paths.get(dir.toString(), "symlink.txt");
    //We create a symbolic link inside of the permitted folder pointing to a file outside of the permitted folder. This should be failing.
    Files.createSymbolicLink(symlink, f2);
    Assert.assertFalse(fileLoader.isFileLocatedInDirectory(dir, symlink));
    Files.delete(symlink);
    Files.delete(f2);

}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected static void cleanUp(long delay) throws Exception {
    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        if (syncAccount == null) {
            return;
        }/*from  w ww  .  j av  a  2  s  .c  om*/

        Files.walkFileTree(Paths.get(syncAccount.getFilePathName()), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                    throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

        });
    }

    pause(delay);

    SyncEngine.stop();

    Files.walkFileTree(Paths.get(_rootFilePathName), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

            Files.delete(filePath);

            return FileVisitResult.CONTINUE;
        }

    });

    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        SyncSystemTestUtil.deleteUser(syncAccount.getUserId(), _syncAccount.getSyncAccountId());

        SyncAccountService.deleteSyncAccount(syncAccountId);
    }

    SyncAccountService.deleteSyncAccount(_syncAccount.getSyncAccountId());
}

From source file:org.discosync.ApplySyncPack.java

/**
 * Apply a syncpack to a target directory.
 *///www  .ja va2 s. c o  m
protected void applySyncPack(String syncPackDir, String targetDir) throws SQLException, IOException {

    // read file operations from database
    File fileOpDbFile = new File(syncPackDir, "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();

    Iterator<FileListEntry> it = db.getFileListOperationIterator();

    Path syncFileBaseDir = Paths.get(syncPackDir, "files");
    String syncFileBaseDirStr = syncFileBaseDir.toAbsolutePath().toString();

    int filesCopied = 0;
    int filesReplaced = 0;
    int filesDeleted = 0;
    long copySize = 0L;
    long deleteSize = 0L;

    // Collect directories during processing.
    List<FileListEntry> directoryOperations = new ArrayList<>();

    // First process all files, then the directories
    while (it.hasNext()) {

        FileListEntry e = it.next();

        // Remember directories
        if (e.isDirectory()) {
            directoryOperations.add(e);
            continue;
        }

        String path = e.getPath();
        Path sourcePath = Paths.get(syncFileBaseDirStr, path); // may not exist
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // copy new file, target files should not exist
            if (Files.exists(targetPath)) {
                System.out
                        .println("Error: the file should not exist: " + targetPath.toAbsolutePath().toString());
            } else {
                if (!Files.exists(targetPath.getParent())) {
                    Files.createDirectories(targetPath.getParent());
                }

                Files.copy(sourcePath, targetPath);
                filesCopied++;
                copySize += e.getSize();
            }

        } else if (e.getOperation() == FileOperations.REPLACE) {
            // replace existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            filesReplaced++;
            copySize += e.getSize();

        } else if (e.getOperation() == FileOperations.DELETE) {
            // delete existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            } else {
                long fileSize = Files.size(targetPath);
                if (fileSize != e.getSize()) {
                    // show info, delete anyway
                    System.out.println(
                            "Info: the file size is different: " + targetPath.toAbsolutePath().toString());
                }
                deleteSize += fileSize;
                Files.delete(targetPath);
                filesDeleted++;
            }
        }
    }

    db.close();

    // Sort directory list to ensure directories are deleted bottom-up (first /dir1/dir2, then /dir1)
    Collections.sort(directoryOperations, new Comparator<FileListEntry>() {
        @Override
        public int compare(FileListEntry e1, FileListEntry e2) {
            return e2.getPath().compareTo(e1.getPath().toString());
        }
    });

    // Now process directories - create and delete empty directories
    for (FileListEntry e : directoryOperations) {

        String path = e.getPath();
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // create directory if needed
            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }
        } else if (e.getOperation() == FileOperations.DELETE) {

            if (!Files.exists(targetPath)) {
                System.out.println(
                        "Info: Directory to DELETE does not exist: " + targetPath.toAbsolutePath().toString());

            } else if (!Files.isDirectory(targetPath, LinkOption.NOFOLLOW_LINKS)) {
                System.out.println("Info: Directory to DELETE is not a directory, but a file: "
                        + targetPath.toAbsolutePath().toString());

            } else if (!Utils.isDirectoryEmpty(targetPath)) {
                System.out.println("Info: Directory to DELETE is not empty, but should be empty: "
                        + targetPath.toAbsolutePath().toString());

            } else {
                // delete directory
                Files.delete(targetPath);
            }
        }
    }

    System.out.println("Apply of syncpack '" + syncPackDir + "' to directory '" + targetDir + "' finished.");
    System.out.println("Files copied  : " + String.format("%,d", filesCopied));
    System.out.println("Files replaced: " + String.format("%,d", filesReplaced));
    System.out.println("Files deleted : " + String.format("%,d", filesDeleted));
    System.out.println("Bytes copied  : " + String.format("%,d", copySize));
    System.out.println("Bytes deleted : " + String.format("%,d", deleteSize));
}

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

protected Map<String, String> readZipArchive(InputStream inputStream) throws IOException {
    Map<String, String> data = new HashMap<String, String>();
    Path tempFile = writeTemporaryArchiveFile(inputStream, "zip");
    ZipFile zip = new ZipFile(tempFile.toFile());
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(zip.getInputStream(entry), bos);
        data.put(entry.getName(), DigestUtils.md5Hex(bos.toByteArray()));
    }//w w w  .j  av  a 2  s  . co  m
    zip.close();
    Files.delete(tempFile);
    return data;
}

From source file:com.adobe.acs.commons.dam.audio.watson.impl.TranscriptionProcess.java

@Override
@SuppressWarnings("squid:S1141")
public Serializable processAudio(Asset asset, ResourceResolver resourceResolver, File tempFile,
        ExecutableLocator locator, File workingDir, MetaDataMap args) throws AudioException {
    final long start = System.currentTimeMillis();
    String jobId = null;//  w ww . ja va  2 s.c om

    log.info("processing asset [{}]...", asset.getPath());

    VideoProfile profile = VideoProfile.get(resourceResolver, profileName);
    if (profile != null) {
        log.info("processAudio: creating audio using profile [{}]", profileName);
        // creating temp working directory for ffmpeg
        FFMpegWrapper ffmpegWrapper = FFMpegWrapper.fromProfile(tempFile, profile, workingDir);
        ffmpegWrapper.setExecutableLocator(locator);
        try {
            final File transcodedAudio = ffmpegWrapper.transcode();
            FileInputStream stream = new FileInputStream(transcodedAudio);
            jobId = transcriptionService.startTranscriptionJob(stream, ffmpegWrapper.getOutputMimetype());
            IOUtils.closeQuietly(stream);
            try {
                Files.delete(transcodedAudio.toPath());
            } catch (Exception e) {
                log.error(
                        "Transcoded audio file @ " + transcodedAudio.getAbsolutePath() + " coud not be deleted",
                        e);
            }
        } catch (IOException e) {
            log.error("processAudio: failed creating audio from profile [{}]: {}", profileName, e.getMessage());
        }
    }
    if (log.isInfoEnabled()) {
        final long time = System.currentTimeMillis() - start;
        log.info("finished initial processing of asset [{}] in [{}ms].", asset.getPath(), time);
    }
    return jobId;
}

From source file:com.vaushell.superpipes.nodes.buffer.N_Buffer.java

private Message popMessage() throws IOException, ClassNotFoundException {
    if (messageIDs.isEmpty()) {
        return null;
    }//from  w  w  w.  j  a va 2  s  .c o  m

    final Long ID = messageIDs.pollFirst();

    final Path p = messagesPath.resolve(Long.toString(ID));

    final Message m = readMessage(p);

    Files.delete(p);

    return m;
}