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:org.wso2.carbon.apimgt.core.util.APIFileUtils.java

/**
 * Delete a given file/*  ww w  .  j ava2  s  .  c  o m*/
 *
 * @param path Path to the file to be deleted
 * @throws APIMgtDAOException if unable to delete the file
 */
public static void deleteFile(String path) throws APIMgtDAOException {
    try {
        Files.delete(Paths.get(path));
    } catch (IOException e) {
        String errorMsg = "Error while deleting file : " + path;
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {/*from   ww  w .  j  a v a  2  s  .  co m*/
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:org.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java

private void clearLogs(final Path path) throws IOException {
    final String expectedName = path.getFileName().toString();
    Files.walkFileTree(path.getParent(), new SimpleFileVisitor<Path>() {
        @Override//  w ww.j a v  a2  s . c o m
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String currentName = file.getFileName().toString();
            if (currentName.startsWith(expectedName)) {
                Files.delete(file);
            }
            return super.visitFile(file, attrs);
        }
    });
}

From source file:ch.bender.evacuate.Runner.java

/**
 * run/*from w  ww  .j  a v a2 s  .c  o  m*/
 * <p>
 * @throws Exception 
 */
public void run() throws Exception {
    checkDirectories();
    initExcludeMatchers();

    myEvacuateCandidates = new TreeMap<>();
    myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>());
    myFutures = new HashSet<>();
    myExclusionDirCount = 0;
    myEvacuationDirCount = 0;
    myExclusionFileCount = 0;
    myEvacuationFileCount = 0;

    Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            return Runner.this.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if ("System Volume Information".equals((dir.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return Runner.this.preVisitDirectory(dir, attrs);
        }

    });

    if (myEvacuateCandidates.size() == 0) {
        myLog.info("No candidates for evacuation found");
    } else {
        StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:");
        myEvacuateCandidates.keySet().forEach(p -> sb.append("\n    " + p.toString()));
        myLog.info(sb.toString());
    }

    if (myDryRun) {
        myLog.debug("DryRun flag is set. Doing nothing");
        return;
    }

    if (myFutures.size() > 0) {
        myLog.debug("Waiting for all async tasks to complete");
        CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get();
    }

    if (myFailedChainPreparations.size() > 0) {
        for (Path path : myFailedChainPreparations.keySet()) {
            myLog.error("exception occured", myFailedChainPreparations.get(path));
        }

        throw new Exception("chain preparation failed. See above error messages");
    }

    for (Path src : myEvacuateCandidates.keySet()) {
        Path dst = myEvacuateCandidates.get(src);
        Path dstParent = dst.getParent();

        if (Files.notExists(dstParent)) {
            Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src
        }

        if (myMove) {
            try {
                myLog.debug(
                        "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                myLog.warn("Atomic move not supported. Try copy and then delete");

                if (Files.isDirectory(src)) {
                    myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyDirectory(src.toFile(), dst.toFile());
                    myLog.debug("Delete folder \"" + src.toString() + "\"");
                    FileUtils.deleteDirectory(src.toFile());
                } else {
                    myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyFile(src.toFile(), dst.toFile());
                    myLog.debug("Delete file \"" + src.toString() + "\"");
                    Files.delete(src);
                }
            }

        } else {
            if (Files.isDirectory(src)) {
                myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyDirectory(src.toFile(), dst.toFile());
            } else {
                myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyFile(src.toFile(), dst.toFile());
            }
        }
    }

    myLog.info("\nSuccessfully terminated." + "\n             Evacuated  Skipped" + "\n    Files  : "
            + StringUtils.leftPad("" + myEvacuationDirCount, 9)
            + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n    Folders: "
            + StringUtils.leftPad("" + myEvacuationFileCount, 9)
            + StringUtils.leftPad("" + myExclusionFileCount, 9));
}

From source file:org.apache.beam.sdk.io.LocalFileSystem.java

@Override
protected void delete(Collection<LocalResourceId> resourceIds) throws IOException {
    for (LocalResourceId resourceId : resourceIds) {
        try {/* ww  w . java2 s.com*/
            Files.delete(resourceId.getPath());
        } catch (NoSuchFileException e) {
            LOG.info("Ignoring failed deletion of file {} which already does not exist: {}", resourceId, e);
        }
    }
}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

protected static void deleteDirectory(final Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override//w  ww.j a v a2  s.c  o m
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

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

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

        @Override
        public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
            throw exc;
        }
    });
}

From source file:org.cirdles.squid.web.SquidReportingService.java

public Path generateReports(String myFileName, InputStream prawnFile, InputStream taskFile, boolean useSBM,
        boolean userLinFits, String refMatFilter, String concRefMatFilter, String preferredIndexIsotopeName)
        throws IOException, JAXBException, SAXException {

    IndexIsoptopesEnum preferredIndexIsotope = IndexIsoptopesEnum.valueOf(preferredIndexIsotopeName);

    // Posix attributes added to support web service on Linux - ignoring windows for now
    Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ);

    // detect if prawnfile is zipped
    boolean prawnIsZip = false;
    String fileName = "";
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    } else if (myFileName.toLowerCase().endsWith(".zip")) {
        fileName = FilenameUtils.removeExtension(myFileName);
        prawnIsZip = true;/*  ww w  .  j  a va2s .c o  m*/
    } else {
        fileName = myFileName;
    }

    SquidProject squidProject = new SquidProject();
    prawnFileHandler = squidProject.getPrawnFileHandler();

    CalamariFileUtilities.initSampleParametersModels();

    Path reportsZip = null;
    Path reportsFolder = null;
    try {
        Path uploadDirectory = Files.createTempDirectory("upload");
        Path uploadDirectory2 = Files.createTempDirectory("upload2");

        Path prawnFilePath;
        Path taskFilePath;
        if (prawnIsZip) {
            Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip");
            Files.copy(prawnFile, prawnFilePathZip);
            prawnFilePath = extractZippedFile(prawnFilePathZip.toFile(), uploadDirectory.toFile());
        } else {
            prawnFilePath = uploadDirectory.resolve("prawn-file.xml");
            Files.copy(prawnFile, prawnFilePath);
        }

        taskFilePath = uploadDirectory2.resolve("task-file.xls");
        Files.copy(taskFile, taskFilePath);

        ShrimpDataFileInterface prawnFileData = prawnFileHandler
                .unmarshallPrawnFileXML(prawnFilePath.toString(), true);
        squidProject.setPrawnFile(prawnFileData);

        // hard-wired for now
        squidProject.getTask().setCommonPbModel(CommonPbModel.getDefaultModel("GA Common Lead 2018", "1.0"));
        squidProject.getTask().setPhysicalConstantsModel(
                PhysicalConstantsModel.getDefaultModel(SQUID2_DEFAULT_PHYSICAL_CONSTANTS_MODEL_V1, "1.0"));
        File squidTaskFile = taskFilePath.toFile();

        squidProject.createTaskFromImportedSquid25Task(squidTaskFile);

        squidProject.setDelimiterForUnknownNames("-");

        TaskInterface task = squidProject.getTask();
        task.setFilterForRefMatSpotNames(refMatFilter);
        task.setFilterForConcRefMatSpotNames(concRefMatFilter);
        task.setUseSBM(useSBM);
        task.setUserLinFits(userLinFits);
        task.setSelectedIndexIsotope(preferredIndexIsotope);

        // process task           
        task.applyTaskIsotopeLabelsToMassStations();

        Path calamariReportsFolderAliasParent = Files.createTempDirectory("reports-destination");
        Path calamariReportsFolderAlias = calamariReportsFolderAliasParent
                .resolve(DEFAULT_SQUID3_REPORTS_FOLDER.getName() + "-from Web Service");
        File reportsDestinationFile = calamariReportsFolderAlias.toFile();

        reportsEngine = prawnFileHandler.getReportsEngine();
        prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);
        reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);

        reportsEngine.produceReports(task.getShrimpFractions(), (ShrimpFraction) task.getUnknownSpots().get(0),
                task.getReferenceMaterialSpots().size() > 0
                        ? (ShrimpFraction) task.getReferenceMaterialSpots().get(0)
                        : (ShrimpFraction) task.getUnknownSpots().get(0),
                true, false);

        squidProject.produceTaskAudit();

        squidProject.produceUnknownsCSV(true);
        squidProject.produceReferenceMaterialCSV(true);
        // next line report will show only super sample for now
        squidProject.produceUnknownsBySampleForETReduxCSV(true);

        Files.delete(prawnFilePath);

        reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReports().getParentFile().getPath());

    } catch (IOException | JAXBException | SAXException | SquidException iOException) {

        Path config = Files.createTempFile("SquidWebServiceMessage", "txt",
                PosixFilePermissions.asFileAttribute(perms));
        try (BufferedWriter writer = Files.newBufferedWriter(config, StandardCharsets.UTF_8)) {
            writer.write("Squid Reporting web service was not able to process supplied files.");
            writer.newLine();
            writer.write(iOException.getMessage());
            writer.newLine();
        }
        File message = config.toFile();

        Path messageDirectory = Files.createTempDirectory("message");
        Path messageFilePath = messageDirectory.resolve("Squid Web Service Message.txt");
        Files.copy(message.toPath(), messageFilePath);

        reportsFolder = messageFilePath.getParent();
    }

    reportsZip = ZipUtility.recursivelyZip(reportsFolder);
    FileUtilities.recursiveDelete(reportsFolder);

    return reportsZip;
}

From source file:io.werval.gradle.ApplicationPluginIntegTest.java

@After
public void cleanupDevShellLock() throws Exception {
    if (devshellLock.exists()) {
        Files.delete(devshellLock.toPath());
    }
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Asynchronously loads the given file/*from w ww. jav a  2  s  . c  om*/
 * @param url the URL to load
 * @param path the path to save the file to
 */
private Future<Path> asyncLoadFile(final String url, final Path path) {
    Callable<Path> job = () -> {
        long t0 = System.currentTimeMillis();

        // For the resulting file, drop the ".download" suffix
        String name = path.getFileName().toString();
        name = name.substring(0, name.length() - DOWNLOAD_SUFFIX.length());

        try {

            // Set up a few timeouts and fetch the attachment
            URLConnection con = new URL(url).openConnection();
            con.setConnectTimeout(60 * 1000); // 1 minute
            con.setReadTimeout(60 * 60 * 1000); // 1 hour

            if (!StringUtils.isEmpty(authHeader)) {
                con.setRequestProperty("Authorization", authHeader);
            }

            try (ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
                    FileOutputStream fos = new FileOutputStream(path.toFile())) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
            log.info(String.format("Copied %s -> %s in %d ms", url, path, System.currentTimeMillis() - t0));

        } catch (Exception e) {
            log.log(Level.SEVERE, "Failed downloading " + url + ": " + e.getMessage());

            // Delete the old file
            if (Files.exists(path)) {
                try {
                    Files.delete(path);
                } catch (IOException e1) {
                    log.finer("Failed deleting old file " + path);
                }
            }

            // Save an error file
            Path errorFile = path.getParent().resolve(name + ".err.txt");
            try (PrintStream err = new PrintStream(new FileOutputStream(errorFile.toFile()))) {
                e.printStackTrace(err);
            } catch (IOException ex) {
                log.finer("Failed generating error file " + errorFile);
            }
            return errorFile;
        }

        Path resultPath = path.getParent().resolve(name);
        try {
            Files.move(path, resultPath);
        } catch (IOException e) {
            log.log(Level.SEVERE, "Failed renaming path " + path + ": " + e.getMessage());
        }
        return resultPath;
    };

    log.info("Submitting new job: " + url);
    return processPool.submit(job);
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public boolean delete(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    boolean isDir = Files.isDirectory(file);
    if (!Files.exists(file)) {
        logger.error("Requested file not exits: {}", file.toAbsolutePath());
        FilemanagerException.Key key = (isDir) ? FilemanagerException.Key.DirectoryNotExist
                : FilemanagerException.Key.FileNotExists;
        throw new FilemanagerException(FilemanagerAction.DELETE, key, file.getFileName().toString());
    }//ww w.ja  v a 2 s .  c  o m
    boolean success = false;
    if (isDir) {
        try {
            FileUtils.deleteDirectory(file.toFile());
            success = true;
        } catch (IOException e) {
        }
    } else {
        try {
            Files.delete(file);
            success = true;
        } catch (IOException e) {
        }
    }
    if (!success)
        throw new FilemanagerException(FilemanagerAction.DELETE,
                FilemanagerException.Key.InvalidDirectoryOrFile, FilenameUtils.getName(backendPath));
    return isDir;
}