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:com.dell.asm.asmcore.asmmanager.util.ServiceTemplateUtil.java

/**
 * Zip attachments and template content, encrypt zip file and return base64 encoded.
 * @param template//from   w  w  w  .ja v  a  2 s.  co  m
 * @param password
 * @return file name
 * @throws AsmManagerRuntimeException
 */
public String exportTemplate(ServiceTemplate template, String password) throws AsmManagerRuntimeException {
    String stringTemplate = MarshalUtil.marshal(template);

    ensureTemplateAttachmentsFolderExists();

    // This is the tar file name.
    long currenttime = System.currentTimeMillis();

    String filename = "template.tmp";
    String foldername = "/tmp/template_" + currenttime;
    String zipFilename = foldername + ".zip";
    String[] command;
    CommandResponse cmdresponse = null;
    ExecuteSystemCommands cmdRunner = ExecuteSystemCommands.getInstance();

    Path tempFolder = Paths.get(foldername);
    Path zipFilePath = Paths.get(zipFilename);

    if (Files.exists(tempFolder)) {
        try {
            Files.delete(tempFolder);
        } catch (IOException e) {
            LOGGER.error(e);
            throw new AsmManagerRuntimeException("Cannot delete directory: " + tempFolder);
        }
    }

    try {
        Files.createDirectory(tempFolder);
    } catch (IOException e) {
        LOGGER.error(e);
        throw new AsmManagerRuntimeException("Cannot create directory: " + tempFolder);
    }

    writeToFile(foldername, filename, stringTemplate);

    // zip all attachments
    File attachPath = new File(TEMPLATE_ATTACHMENT_DIR + template.getId());
    if (attachPath.exists() && attachPath.isDirectory() && attachPath.list().length > 0) {
        try {
            command = new String[] { "/bin/bash", "-c",
                    "/bin/cp -r " + attachPath.getAbsolutePath() + "/* " + tempFolder };
            cmdresponse = cmdRunner.runCommandWithConsoleOutput(command);
        } catch (Exception e) {
            LOGGER.error(e);
            throw new AsmManagerRuntimeException("Cannot copy attachments to temp folder: " + tempFolder);
        }
        if (!cmdresponse.getReturnCode().equals("0")) {
            throw new AsmManagerRuntimeException("Copying of template attachments failed");
        }
    }

    command = new String[] { "/bin/bash", "-c", "/usr/bin/zip -j " + zipFilename + " " + tempFolder + "/*" };

    try {
        cmdresponse = cmdRunner.runCommandWithConsoleOutput(command);
    } catch (Exception e) {
        LOGGER.error("Command execution failed: " + command, e);
        throw new AsmManagerRuntimeException(e);
    } finally {
        try {
            FileUtils.deleteDirectory(new File(tempFolder.toString()));
        } catch (IOException e) {
            LOGGER.error("Cannot delete temp folder: " + tempFolder, e);
        }
    }
    if (!cmdresponse.getReturnCode().equals("0")) {
        throw new AsmManagerRuntimeException("Zipping of template attachments failed");
    }

    command = new String[] { "/bin/bash", "-c",
            "echo " + ExecuteSystemCommands.sanitizeShellArgument(password)
                    + " | gpg --batch -q --passphrase-fd 0 -c "
                    + ExecuteSystemCommands.sanitizeShellArgument(zipFilename) };
    try {
        cmdresponse = cmdRunner.callCommand(command);
    } catch (Exception e) {
        LOGGER.error("Command execution failed: " + command, e);
        throw new AsmManagerRuntimeException(e);
    } finally {
        try {
            Files.delete(zipFilePath);
        } catch (IOException e) {
            LOGGER.error("Cannot delete zip file: " + zipFilePath, e);
        }
    }

    LOGGER.debug("GPG return code: " + cmdresponse.getReturnCode() + " Return message: "
            + cmdresponse.getReturnMessage());
    if (!cmdresponse.getReturnCode().equals("0")) {
        throw new AsmManagerRuntimeException("Encryption of template failed");
    }

    return zipFilename + ".gpg";
}

From source file:org.apache.storm.localizer.AsyncLocalizer.java

private LocalizedResource downloadBlob(Map<String, Object> conf, String key, File localFile, String user,
        boolean uncompress, boolean isUpdate) throws AuthorizationException, KeyNotFoundException, IOException {
    ClientBlobStore blobstore = null;/*from  ww  w .j  a  v a2 s.  c o m*/
    try {
        blobstore = getClientBlobStore();
        long nimbusBlobVersion = ServerUtils.nimbusVersionOfBlob(key, blobstore);
        long oldVersion = ServerUtils.localVersionOfBlob(localFile.toString());
        FileOutputStream out = null;
        PrintWriter writer = null;
        int numTries = 0;
        String localizedPath = localFile.toString();
        String localFileWithVersion = ServerUtils.constructBlobWithVersionFileName(localFile.toString(),
                nimbusBlobVersion);
        String localVersionFile = ServerUtils.constructVersionFileName(localFile.toString());
        String downloadFile = localFileWithVersion;
        if (uncompress) {
            // we need to download to temp file and then unpack into the one requested
            downloadFile = new File(localFile.getParent(), TO_UNCOMPRESS + localFile.getName()).toString();
        }
        while (numTries < blobDownloadRetries) {
            out = new FileOutputStream(downloadFile);
            numTries++;
            try {
                if (!ServerUtils.canUserReadBlob(blobstore.getBlobMeta(key), user, conf)) {
                    throw new AuthorizationException(user + " does not have READ access to " + key);
                }
                InputStreamWithMeta in = blobstore.getBlob(key);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, len);
                }
                out.close();
                in.close();
                if (uncompress) {
                    ServerUtils.unpack(new File(downloadFile), new File(localFileWithVersion));
                    LOG.debug("uncompressed " + downloadFile + " to: " + localFileWithVersion);
                }

                // Next write the version.
                LOG.info("Blob: " + key + " updated with new Nimbus-provided version: " + nimbusBlobVersion
                        + " local version was: " + oldVersion);
                // The false parameter ensures overwriting the version file, not appending
                writer = new PrintWriter(new BufferedWriter(new FileWriter(localVersionFile, false)));
                writer.println(nimbusBlobVersion);
                writer.close();

                try {
                    setBlobPermissions(conf, user, localFileWithVersion);
                    setBlobPermissions(conf, user, localVersionFile);

                    // Update the key.current symlink. First create tmp symlink and do
                    // move of tmp to current so that the operation is atomic.
                    String tmp_uuid_local = java.util.UUID.randomUUID().toString();
                    LOG.debug("Creating a symlink @" + localFile + "." + tmp_uuid_local + " , " + "linking to: "
                            + localFile + "." + nimbusBlobVersion);
                    File uuid_symlink = new File(localFile + "." + tmp_uuid_local);

                    Files.createSymbolicLink(uuid_symlink.toPath(), Paths.get(ServerUtils
                            .constructBlobWithVersionFileName(localFile.toString(), nimbusBlobVersion)));
                    File current_symlink = new File(
                            ServerUtils.constructBlobCurrentSymlinkName(localFile.toString()));
                    Files.move(uuid_symlink.toPath(), current_symlink.toPath(), ATOMIC_MOVE);
                } catch (IOException e) {
                    // if we fail after writing the version file but before we move current link we need to
                    // restore the old version to the file
                    try {
                        PrintWriter restoreWriter = new PrintWriter(
                                new BufferedWriter(new FileWriter(localVersionFile, false)));
                        restoreWriter.println(oldVersion);
                        restoreWriter.close();
                    } catch (IOException ignore) {
                    }
                    throw e;
                }

                String oldBlobFile = localFile + "." + oldVersion;
                try {
                    // Remove the old version. Note that if a number of processes have that file open,
                    // the OS will keep the old blob file around until they all close the handle and only
                    // then deletes it. No new process will open the old blob, since the users will open the
                    // blob through the "blob.current" symlink, which always points to the latest version of
                    // a blob. Remove the old version after the current symlink is updated as to not affect
                    // anyone trying to read it.
                    if ((oldVersion != -1) && (oldVersion != nimbusBlobVersion)) {
                        LOG.info("Removing an old blob file:" + oldBlobFile);
                        Files.delete(Paths.get(oldBlobFile));
                    }
                } catch (IOException e) {
                    // At this point we have downloaded everything and moved symlinks.  If the remove of
                    // old fails just log an error
                    LOG.error("Exception removing old blob version: " + oldBlobFile);
                }

                break;
            } catch (AuthorizationException ae) {
                // we consider this non-retriable exceptions
                if (out != null) {
                    out.close();
                }
                new File(downloadFile).delete();
                throw ae;
            } catch (IOException | KeyNotFoundException e) {
                if (out != null) {
                    out.close();
                }
                if (writer != null) {
                    writer.close();
                }
                new File(downloadFile).delete();
                if (uncompress) {
                    try {
                        FileUtils.deleteDirectory(new File(localFileWithVersion));
                    } catch (IOException ignore) {
                    }
                }
                if (!isUpdate) {
                    // don't want to remove existing version file if its an update
                    new File(localVersionFile).delete();
                }

                if (numTries < blobDownloadRetries) {
                    LOG.error("Failed to download blob, retrying", e);
                } else {
                    throw e;
                }
            }
        }
        return new LocalizedResource(key, localizedPath, uncompress);
    } finally {
        if (blobstore != null) {
            blobstore.shutdown();
        }
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Deletes a complete directory recursively, using Java NIO
 * //from ww  w . ja  v  a2s.  com
 * @param dir
 *          directory to delete
 * @throws IOException
 */
public static void deleteDirectoryRecursive(Path dir) throws IOException {
    if (!Files.exists(dir)) {
        return;
    }

    LOGGER.info("Deleting complete directory: " + dir);
    Files.walkFileTree(dir, new FileVisitor<Path>() {

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

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

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            LOGGER.warn("Could not delete " + file + "; " + exc.getMessage());
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public void addFiles(DatasetVersion version, List<DataFile> newFiles) {
    if (newFiles != null && newFiles.size() > 0) {
        // final check for duplicate file names; 
        // we tried to make the file names unique on upload, but then 
        // the user may have edited them on the "add files" page, and 
        // renamed FOOBAR-1.txt back to FOOBAR.txt...

        checkForDuplicateFileNamesFinal(version, newFiles);

        Dataset dataset = version.getDataset();

        try {//  w ww . j av a2 s . co m
            if (dataset.getFileSystemDirectory() != null && !Files.exists(dataset.getFileSystemDirectory())) {
                /* Note that "createDirectories()" must be used - not 
                 * "createDirectory()", to make sure all the parent 
                 * directories that may not yet exist are created as well. 
                 */

                Files.createDirectories(dataset.getFileSystemDirectory());
            }
        } catch (IOException dirEx) {
            logger.severe("Failed to create study directory " + dataset.getFileSystemDirectory().toString());
            return;
            // TODO:
            // Decide how we are communicating failure information back to 
            // the page, and what the page should be doing to communicate
            // it to the user - if anything. 
            // -- L.A. 
        }

        if (dataset.getFileSystemDirectory() != null && Files.exists(dataset.getFileSystemDirectory())) {
            for (DataFile dataFile : newFiles) {
                String tempFileLocation = getFilesTempDirectory() + "/" + dataFile.getStorageIdentifier();

                FileMetadata fileMetadata = dataFile.getFileMetadatas().get(0);
                String fileName = fileMetadata.getLabel();

                // temp dbug line
                System.out.println("ADDING FILE: " + fileName + "; for dataset: " + dataset.getGlobalId());

                // These are all brand new files, so they should all have 
                // one filemetadata total. -- L.A. 
                boolean metadataExtracted = false;

                if (ingestableAsTabular(dataFile)) {
                    /*
                     * Note that we don't try to ingest the file right away - 
                     * instead we mark it as "scheduled for ingest", then at 
                     * the end of the save process it will be queued for async. 
                     * ingest in the background. In the meantime, the file 
                     * will be ingested as a regular, non-tabular file, and 
                     * appear as such to the user, until the ingest job is
                     * finished with the Ingest Service.
                     */
                    dataFile.SetIngestScheduled();
                } else if (fileMetadataExtractable(dataFile)) {

                    try {
                        // FITS is the only type supported for metadata 
                        // extraction, as of now. -- L.A. 4.0 
                        dataFile.setContentType("application/fits");
                        metadataExtracted = extractMetadata(tempFileLocation, dataFile, version);
                    } catch (IOException mex) {
                        logger.severe("Caught exception trying to extract indexable metadata from file "
                                + fileName + ",  " + mex.getMessage());
                    }
                    if (metadataExtracted) {
                        logger.fine("Successfully extracted indexable metadata from file " + fileName);
                    } else {
                        logger.fine("Failed to extract indexable metadata from file " + fileName);
                    }
                }

                // Try to save the file in its permanent location: 

                String storageId = dataFile.getStorageIdentifier().replaceFirst("^tmp://", "");

                Path tempLocationPath = Paths.get(getFilesTempDirectory() + "/" + storageId);
                WritableByteChannel writeChannel = null;
                FileChannel readChannel = null;

                try {

                    DataFileIO dataAccess = dataFile.getAccessObject();

                    /* 
                     This commented-out code demonstrates how to copy bytes
                     from a local InputStream (or a readChannel) into the
                     writable byte channel of a Dataverse DataAccessIO object:
                    */
                    /*
                    dataAccess.open(DataAccessOption.WRITE_ACCESS);
                                                
                    writeChannel = dataAccess.getWriteChannel();
                    readChannel = new FileInputStream(tempLocationPath.toFile()).getChannel();
                                                
                    long bytesPerIteration = 16 * 1024; // 16K bytes
                    long start = 0;
                    while ( start < readChannel.size() ) {
                    readChannel.transferTo(start, bytesPerIteration, writeChannel);
                    start += bytesPerIteration;
                    }
                    */

                    /* 
                    But it's easier to use this convenience method from the
                    DataAccessIO: 
                            
                    (if the underlying storage method for this file is 
                    local filesystem, the DataAccessIO will simply copy 
                    the file using Files.copy, like this:
                            
                    Files.copy(tempLocationPath, dataAccess.getFileSystemLocation(), StandardCopyOption.REPLACE_EXISTING);
                    */

                    dataAccess.copyPath(tempLocationPath);

                    // Set filesize in bytes
                    // 
                    dataFile.setFilesize(dataAccess.getSize());

                } catch (IOException ioex) {
                    logger.warning("Failed to save the file, storage id " + dataFile.getStorageIdentifier());
                } finally {
                    if (readChannel != null) {
                        try {
                            readChannel.close();
                        } catch (IOException e) {
                        }
                    }
                    if (writeChannel != null) {
                        try {
                            writeChannel.close();
                        } catch (IOException e) {
                        }
                    }
                }

                // delete the temporary file: 
                try {
                    logger.fine("Will attempt to delete the temp file " + tempLocationPath.toString());
                    // also, delete a temporary thumbnail image file, if exists:
                    // (TODO: probably not a very good style, that the size of the thumbnail 
                    // is hard-coded here; it may change in the future...)
                    Path tempThumbnailPath = Paths.get(tempLocationPath.toString() + ".thumb64");
                    Files.delete(tempLocationPath);
                    if (tempThumbnailPath.toFile().exists()) {
                        Files.delete(tempThumbnailPath);
                    }
                } catch (IOException ex) {
                    // (non-fatal - it's just a temp file.)
                    logger.warning("Failed to delete temp file " + tempLocationPath.toString());
                }
                // Any necessary post-processing: 
                performPostProcessingTasks(dataFile);
            }
        }
    }
}

From source file:com.dell.asm.asmcore.asmmanager.util.ServiceTemplateUtil.java

/**
 * Decrypt, unzip and copy attachments to template folder.
 * @param encryptedTemplateFileData encrypted template file data
 * @param password/*from   w w w.j av a2s. c o  m*/
 * @return
 * @throws AsmManagerRuntimeException
 */
public static ServiceTemplate importTemplate(byte[] encryptedTemplateFileData, String password)
        throws AsmManagerRuntimeException {

    ServiceTemplate svc = null;

    if (encryptedTemplateFileData != null && encryptedTemplateFileData.length > 0) {
        ensureTemplateAttachmentsFolderExists();

        // This is the tar file name.
        long currenttime = System.currentTimeMillis();

        String filename = "template_" + currenttime + ".gpg";
        String restoredFile = "template_" + currenttime + ".zip";
        String tempFolder = "/tmp/template_" + currenttime;

        writeToFile("/tmp", filename, encryptedTemplateFileData);

        CommandResponse cmdresponse = null;
        ExecuteSystemCommands cmdRunner = ExecuteSystemCommands.getInstance();

        String[] command = new String[] { "/bin/bash", "-c",
                "echo " + ExecuteSystemCommands.sanitizeShellArgument(password)
                        + " | gpg --batch -q --utf8-strings --output "
                        + ExecuteSystemCommands.sanitizeShellArgument("/tmp/" + restoredFile)
                        + " --passphrase-fd 0 --decrypt "
                        + ExecuteSystemCommands.sanitizeShellArgument("/tmp/" + filename) };

        try {
            cmdresponse = cmdRunner.callCommand(command);
        } catch (Exception e) {
            LOGGER.error("GPG execution failed", e);
            throw new AsmManagerRuntimeException(e);
        } finally {
            File file = new File("/tmp/" + filename);
            file.delete();
        }

        LOGGER.debug("GPG return code: " + cmdresponse.getReturnCode() + " Return message: "
                + cmdresponse.getReturnMessage());
        if (!cmdresponse.getReturnCode().equals("0")) {
            throw new AsmManagerRuntimeException("Decryption of template failed, invalid file or password");
        }

        String encFil = "/tmp/" + restoredFile;

        // unzip all attachments
        command = new String[] { "/usr/bin/unzip", encFil, "-d" + tempFolder };

        try {
            cmdresponse = cmdRunner.runCommandWithConsoleOutput(command);
        } catch (Exception e) {
            LOGGER.error("Command execution failed: " + command, e);
            throw new AsmManagerRuntimeException(e);
        }

        if (!cmdresponse.getReturnCode().equals("0")) {
            throw new AsmManagerRuntimeException("UnZipping of template attachments failed");
        }

        try {
            Files.delete(Paths.get(encFil));
        } catch (IOException e) {
            LOGGER.error("Cannot delete file " + encFil, e);
        }

        // read template content
        File file = new File(tempFolder + "/template.tmp");
        String content = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            content = IOUtils.toString(is);
        } catch (IOException e) {
            throw new AsmManagerRuntimeException(e);
        } finally {
            if (is != null)
                IOUtils.closeQuietly(is);
        }
        file.delete();

        svc = MarshalUtil.unmarshal(ServiceTemplate.class, content);
        if (svc == null) {
            throw new AsmManagerRuntimeException("Template content is null. Bad import file.");
        }

        // copy
        Path attachPath = Paths.get(TEMPLATE_ATTACHMENT_DIR + svc.getId());
        if (Files.exists(attachPath)) {
            svc.setId(UUID.randomUUID().toString());
            attachPath = Paths.get(TEMPLATE_ATTACHMENT_DIR + svc.getId());
        }
        try {
            Files.createDirectory(attachPath);
        } catch (IOException e) {
            LOGGER.error(e);
            throw new AsmManagerRuntimeException("Cannot create directory: " + attachPath);
        }

        File tmpDir = new File(tempFolder);
        if (tmpDir.exists() && tmpDir.isDirectory()) {
            if (tmpDir.list().length > 0) {
                try {
                    Files.walkFileTree(tmpDir.toPath(), new CopyFileVisitor(attachPath));
                } catch (Exception e) {
                    LOGGER.error(e);
                    throw new AsmManagerRuntimeException(
                            "Cannot copy attachments to template folder: " + attachPath);
                }
            }

            // cleanup
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                LOGGER.error("Cannot delete temp folder: " + tempFolder, e);
            }
        }
    }

    return svc;
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Saves the current config to disk//from ww  w  .  j a v  a 2 s . com
 */
public synchronized void saveConfig() {
    if (!started) {
        return;
    }
    logFine("Saving config (" + getConfigName() + ".config)");

    Path file;
    Path tempFile;
    Path folderFile;
    Path tempFolderFile;
    Path backupFile;
    if (getConfigLocationBase() == null) {
        file = Paths.get(getConfigName() + ".config").toAbsolutePath();
        tempFile = Paths.get(getConfigName() + ".writing.config").toAbsolutePath();
        folderFile = Paths.get(getConfigName() + "-Folder.config").toAbsolutePath();
        tempFolderFile = Paths.get(getConfigName() + "-Folder.writing.config").toAbsolutePath();
        backupFile = Paths.get(getConfigName() + ".config.backup").toAbsolutePath();
    } else {
        file = getConfigLocationBase().resolve(getConfigName() + ".config");
        tempFile = getConfigLocationBase().resolve(getConfigName() + ".writing.config").toAbsolutePath();
        backupFile = getConfigLocationBase().resolve(getConfigName() + ".config.backup");
        folderFile = getConfigLocationBase().resolve(getConfigName() + "-Folder.config");
        tempFolderFile = getConfigLocationBase().resolve(getConfigName() + "-Folder.writing.config")
                .toAbsolutePath();
    }

    try {
        // Backup is done in #backupConfigAssets
        Files.deleteIfExists(backupFile);

        String distName = "PowerFolder";
        if (distribution != null && StringUtils.isNotBlank(distribution.getName())) {
            distName = distribution.getName();
        }

        Properties prev = new Properties();
        if (Files.exists(file)) {
            try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(file))) {
                prev.load(in);
            }
        }

        if (!prev.equals(config.getRegular())) {
            // Store config in misc base
            PropertiesUtil.saveConfig(tempFile, config.getRegular(),
                    distName + " config file (v" + PROGRAM_VERSION + ')');
            Files.deleteIfExists(file);
            try {
                Files.move(tempFile, file);
            } catch (IOException e) {
                Files.copy(tempFile, file);
                Files.delete(tempFile);
            }
        } else {
            if (isFine()) {
                logFine("Not storing config to " + file + ". Base config remains unchanged");
            }
        }

        if (!config.getFolders().isEmpty()) {
            Properties prevFolders = new Properties();
            if (Files.exists(folderFile)) {
                try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(folderFile))) {
                    prevFolders.load(in);
                }
            }
            if (!prevFolders.equals(config.getFolders())) {
                PropertiesUtil.saveConfig(tempFolderFile, config.getFolders(),
                        distName + " folders config file (v" + PROGRAM_VERSION + ')');
                Files.deleteIfExists(folderFile);
                try {
                    Files.move(tempFolderFile, folderFile);
                } catch (IOException e) {
                    Files.copy(tempFolderFile, folderFile);
                    Files.delete(tempFolderFile);
                }
            }
        }
    } catch (IOException e) {
        // FATAL
        logSevere("Unable to save config. " + e, e);
        exit(1);
    } catch (Exception e) {
        // major problem , setting code is wrong
        e.printStackTrace();
        logSevere("major problem , setting code is wrong", e);
    }
}

From source file:io.minio.MinioClient.java

/**
 * Gets object's data in the given bucket and stores it to given file name.
 *
 * </p><b>Example:</b><br>
 * <pre>{@code minioClient.getObject("my-bucketname", "my-objectname", "photo.jpg"); }</pre>
 *
 * @param bucketName  Bucket name./*w w  w.  j  a v  a2 s  .com*/
 * @param objectName  Object name in the bucket.
 * @param fileName    file name.
 *
 * @throws InvalidBucketNameException  upon invalid bucket name is given
 * @throws NoResponseException         upon no response from server
 * @throws IOException                 upon connection error
 * @throws XmlPullParserException      upon parsing response xml
 * @throws ErrorResponseException      upon unsuccessful execution
 * @throws InternalException           upon internal library error
 */
public void getObject(String bucketName, String objectName, String fileName)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException, InvalidArgumentException {
    Path filePath = Paths.get(fileName);
    boolean fileExists = Files.exists(filePath);

    if (fileExists && !Files.isRegularFile(filePath)) {
        throw new InvalidArgumentException(fileName + ": not a regular file");
    }

    ObjectStat objectStat = statObject(bucketName, objectName);
    long length = objectStat.length();
    String etag = objectStat.etag();

    String tempFileName = fileName + "." + etag + ".part.minio";
    Path tempFilePath = Paths.get(tempFileName);
    boolean tempFileExists = Files.exists(tempFilePath);

    if (tempFileExists && !Files.isRegularFile(tempFilePath)) {
        throw new IOException(tempFileName + ": not a regular file");
    }

    long tempFileSize = 0;
    if (tempFileExists) {
        tempFileSize = Files.size(tempFilePath);
        if (tempFileSize > length) {
            Files.delete(tempFilePath);
            tempFileExists = false;
            tempFileSize = 0;
        }
    }

    if (fileExists) {
        long fileSize = Files.size(filePath);
        if (fileSize == length) {
            // already downloaded. nothing to do
            return;
        } else if (fileSize > length) {
            throw new InvalidArgumentException(
                    "'" + fileName + "': object size " + length + " is smaller than file size " + fileSize);
        } else if (!tempFileExists) {
            // before resuming the download, copy filename to tempfilename
            Files.copy(filePath, tempFilePath);
            tempFileSize = fileSize;
            tempFileExists = true;
        }
    }

    InputStream is = null;
    OutputStream os = null;
    try {
        is = getObject(bucketName, objectName, tempFileSize);
        os = Files.newOutputStream(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        long bytesWritten = ByteStreams.copy(is, os);
        is.close();
        os.close();

        if (bytesWritten != length - tempFileSize) {
            throw new IOException(tempFileName + ": unexpected data written.  expected = "
                    + (length - tempFileSize) + ", written = " + bytesWritten);
        }

        Files.move(tempFilePath, filePath, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
}

From source file:org.apache.solr.handler.IndexFetcher.java

/**
 * This simulates File.delete exception-wise, since this class has some strange behavior with it.
 * The only difference is it returns null on success, throws SecurityException on SecurityException,
 * otherwise returns Throwable preventing deletion (instead of false), for additional information.
 *//*from  ww w.jav a 2s .c om*/
static Throwable delete(File file) {
    try {
        Files.delete(file.toPath());
        return null;
    } catch (SecurityException e) {
        throw e;
    } catch (Throwable other) {
        return other;
    }
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Delete all uploaded RDF/XML source files and the corresponding named
 * models//from  www  .j  av  a  2s.c  o m
 *
 * @throws IOException
 */
private void clearSourceFiles() throws IOException {
    if (source.size() > 0) {
        // Delete all uploaded files (if any) and clear the source file list
        for (Path f : source) {
            Files.delete(f);

            // Remove the named model the contains the information in this
            // file
            ds.removeNamedModel(VISA.createModelURI(f.getFileName().toString()));
        }

        source.clear();
    }
}