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.dcm4chee.proxy.forward.ForwardFiles.java

private static void deleteFile(File file) {
    try {//from ww w.j a va  2  s .  co  m
        Files.delete(file.toPath());
        LOG.debug("Delete {}", file);
    } catch (Exception e) {
        LOG.debug("Failed to delete {} - {}", file, e);
    }

    File infoFile = new File(file.getParent(),
            file.getName().substring(0, file.getName().indexOf('.')) + ".info");
    try {
        Files.delete(infoFile.toPath());
        LOG.debug("Delete {}", infoFile);
    } catch (Exception e) {
        LOG.debug("Failed to delete {} - {}", infoFile, e);
    }
    File path = new File(file.getParent());
    if (path.list().length == 0)
        path.delete();
}

From source file:org.roda.core.model.ModelService.java

public synchronized void findOldLogsAndMoveThemToStorage(Path logDirectory, Path currentLogFile)
        throws RequestNotValidException, AuthorizationDeniedException, NotFoundException {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(logDirectory)) {

        for (Path path : directoryStream) {
            if (!path.equals(currentLogFile)) {
                try {
                    StoragePath logPath = ModelUtils.getLogStoragePath(path.getFileName().toString());
                    storage.createBinary(logPath, new FSPathContentPayload(path), false);
                    Files.delete(path);
                } catch (IOException | GenericException | AlreadyExistsException e) {
                    LOGGER.error("Error archiving log file", e);
                }/*from   w w  w. j a  v a 2s.  c o  m*/
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error listing directory for log files", e);
    }
}

From source file:org.structr.web.advanced.DeploymentTest.java

private void doImportExportRoundtrip(final boolean deleteTestDirectory, final boolean cleanDatabase,
        final Function callback) {

    final DeployCommand cmd = app.command(DeployCommand.class);
    final Path tmp = Paths.get("/tmp/structr-deployment-test" + System.currentTimeMillis() + System.nanoTime());

    try {//from ww w .j  a  va 2  s.  c o  m
        if (tmp != null) {

            // export to temp directory
            final Map<String, Object> firstExportParams = new HashMap<>();
            firstExportParams.put("mode", "export");
            firstExportParams.put("target", tmp.toString());

            // execute deploy command
            cmd.execute(firstExportParams);

            if (cleanDatabase) {
                cleanDatabase();
            }

            // apply callback if present
            if (callback != null) {
                callback.apply(null);
            }

            // import from exported source
            final Map<String, Object> firstImportParams = new HashMap<>();
            firstImportParams.put("source", tmp.toString());

            // execute deploy command
            cmd.execute(firstImportParams);

        } else {

            fail("Unable to create temporary directory.");
        }

    } catch (Throwable t) {

        t.printStackTrace();

    } finally {

        if (deleteTestDirectory) {

            try {
                // clean directories
                Files.walkFileTree(tmp, new DeletingFileVisitor());
                Files.delete(tmp);

            } catch (IOException ioex) {
            }
        }
    }
}

From source file:io.snappydata.hydra.cluster.SnappyTest.java

/**
 * Deletes the snappy config generated spcific to test run after successful test execution.
 *//*from ww  w .  ja  v a 2 s. c o  m*/
public static void HydraTask_deleteSnappyConfig() throws IOException {
    String locatorConf = productConfDirPath + sep + "locators";
    String serverConf = productConfDirPath + sep + "servers";
    String leadConf = productConfDirPath + sep + "leads";
    Files.delete(Paths.get(locatorConf));
    Log.getLogWriter().info("locators file deleted");
    Files.delete(Paths.get(serverConf));
    Log.getLogWriter().info("servers file deleted");
    Files.delete(Paths.get(leadConf));
    Log.getLogWriter().info("leads file deleted");
    if (useSplitMode) {
        String slaveConf = productConfDirPath + sep + "slaves";
        String sparkEnvConf = productConfDirPath + sep + "spark-env.sh";
        Files.delete(Paths.get(slaveConf));
        Log.getLogWriter().info("slaves file deleted");
        Files.delete(Paths.get(sparkEnvConf));
        Log.getLogWriter().info("spark-env.sh file deleted");
    }
    // Removing twitter data directories if exists.
    String twitterdata = dtests + "twitterdata";
    String copiedtwitterdata = dtests + "copiedtwitterdata";
    File file = new File(twitterdata);
    if (file.exists()) {
        file.delete();
        Log.getLogWriter().info("Done removing twitter data directory.");
    }
    file = new File(copiedtwitterdata);
    if (file.exists()) {
        file.delete();
        Log.getLogWriter().info("Done removing copiedtwitterdata data directory.");
    }
}

From source file:io.snappydata.hydra.cluster.SnappyTest.java

protected synchronized void generateConfig(String fileName) {
    File file = null;/*from  w w w  .j a  va  2 s .  co m*/
    try {
        String path = productConfDirPath + sep + fileName;
        log().info("File Path is ::" + path);
        file = new File(path);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        } else if (file.exists()) {
            if (isStopMode)
                return;
            file.setWritable(true);
            //file.delete();
            Files.delete(Paths.get(path));
            Log.getLogWriter().info(fileName + " file deleted");
            file.createNewFile();
        }
    } catch (IOException e) {
        String s = "Problem while creating the file : " + file;
        throw new TestException(s, e);
    }
}

From source file:org.domainmath.gui.MainFrame.java

private void exitFinal(ShutDown shutDown) {
    MainFrame.workspace.requestToClearAll();
    MainFrame.reloadWorkspace();/*from ww  w  .ja v  a 2s . c  o  m*/
    octavePanel.quit();
    File f = new File(System.getProperty("user.dir") + File.separator + "scripts" + File.separator + "dmns.m");
    f.deleteOnExit();
    File dir_content[];
    try {
        dir_content = logDir.listFiles();
        for (int i = 0; i < dir_content.length; i++) {
            Files.delete(dir_content[i].toPath());
        }
        Files.delete(logDir.toPath());
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.saveLayout();
    File _f = new File(parent_root + "DomainMath_OctaveDbStack.dat");
    _f.delete();
    saveCurrentDir();
    try {
        FileUtils.deleteDirectory(new File(System.getProperty("user.dir") + File.separator + "doc_cache"));
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    saveFrameSize(this.getWidth(), this.getHeight());
    shutDown.dispose();
    this.dispose();

    System.exit(0);
}

From source file:org.silverpeas.components.kmelia.control.KmeliaSessionController.java

public File exportPublication() {
    if (!isFormatSupported("zip")) {
        throw new KmeliaRuntimeException("Export format not yet supported");
    }/* w  ww.j  a v a2s .  co m*/
    PublicationPK pubPK = getSessionPublication().getDetail().getPK();
    File pdf = null;
    try {
        // create subdir to zip
        String subdir = "ExportPubli_" + pubPK.getId() + "_" + System.currentTimeMillis();
        String fileName = getPublicationExportFileName(getSessionPublication(), getLanguage());
        String subDirPath = FileRepositoryManager.getTemporaryPath() + subdir + File.separator + fileName;
        FileFolderManager.createFolder(subDirPath);
        // generate from the publication a document in PDF
        if (isFormatSupported(DocumentFormat.pdf.name())) {
            pdf = generateDocument(DocumentFormat.pdf, pubPK.getId());
            // copy pdf into zip
            FileRepositoryManager.copyFile(pdf.getPath(), subDirPath + File.separator + pdf.getName());
        }
        // copy files
        new AttachmentImportExport(getUserDetail()).getAttachments(pubPK.toResourceReference(), subDirPath,
                USELESS, null);

        String zipFileName = FileRepositoryManager.getTemporaryPath() + fileName + ".zip";
        // zip PDF and files
        ZipUtil.compressPathToZip(subDirPath, zipFileName);

        return new File(zipFileName);
    } catch (Exception e) {
        throw new KmeliaRuntimeException(e);
    } finally {
        if (pdf != null) {
            try {
                Files.delete(pdf.toPath());
            } catch (IOException e) {
                SilverLogger.getLogger(this).warn(e);
            }
        }
    }
}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

@Override
public Integer moveFilesByPath(String inPath, Integer transportMethodId, Integer orgId, Integer transportId) {
    Integer sysErrors = 0;//from w w  w.j  a v a 2 s.c  o  m

    try {
        fileSystem fileSystem = new fileSystem();
        String fileInPath = fileSystem.setPathFromRoot(inPath);
        File folder = new File(fileInPath);

        //list files
        //we only list visible files
        File[] listOfFiles = folder.listFiles((FileFilter) HiddenFileFilter.VISIBLE);

        Organization orgDetails = organizationmanager.getOrganizationById(orgId);
        String defPath = "/bowlink/" + orgDetails.getcleanURL() + "/input files/";
        String outPath = fileSystem.setPath(defPath);

        //too many variables that could come into play regarding file types, will check files with one method
        //loop files 
        for (File file : listOfFiles) {
            String fileName = file.getName();
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
            Date date = new Date();
            /* Create the batch name (TransportMethodId+OrgId+Date/Time/Seconds) */
            String batchName = new StringBuilder().append(transportMethodId).append(orgId)
                    .append(dateFormat.format(date)).toString();

            if (!fileName.endsWith("_error")) {

                try {

                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

                    //figure out how many active transports are using fileExt method for this particular path
                    List<configurationTransport> transportList = configurationtransportmanager
                            .getTransportListForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    //figure out if files has distinct delimiters
                    List<configurationTransport> transports = configurationtransportmanager
                            .getConfigTransportForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    batchUploads batchInfo = new batchUploads();
                    batchInfo.setOrgId(orgId);
                    batchInfo.settransportMethodId(transportMethodId);
                    batchInfo.setstatusId(4);
                    batchInfo.setstartDateTime(date);
                    batchInfo.setutBatchName(batchName);
                    batchInfo.setOriginalFolder(inPath);

                    Integer batchId = 0;
                    String newFileName = "";
                    Integer statusId = 4;
                    Integer configId = 0;
                    Integer fileSize = 0;
                    Integer encodingId = 1;
                    Integer errorId = 0;

                    if (transportList.size() == 0 || transports.size() == 0) { //neither of them should be 0
                        //no source transport is associated with this method / file
                        batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                        batchInfo.setConfigId(0);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setFileLocation(defPath);
                        batchInfo.setEncodingId(encodingId);
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        //insert error
                        errorId = 13;
                        statusId = 7;
                    } else if (transports.size() == 1) {
                        encodingId = transports.get(0).getEncodingId();
                        configurationTransport ct = configurationtransportmanager
                                .getTransportDetailsByTransportId(transportId);
                        fileSize = ct.getmaxFileSize();
                        if (transportList.size() > 1) {
                            configId = 0;
                            fileSize = configurationtransportmanager.getMinMaxFileSize(fileExt,
                                    transportMethodId);
                        } else {
                            configId = ct.getconfigId();
                        }
                        batchInfo.setConfigId(configId);
                        batchInfo.setContainsHeaderRow(transports.get(0).getContainsHeaderRow());
                        batchInfo.setDelimChar(transports.get(0).getDelimChar());
                        batchInfo.setFileLocation(ct.getfileLocation());
                        outPath = fileSystem.setPath(ct.getfileLocation());
                        batchInfo.setOrgId(orgId);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setEncodingId(encodingId);

                        //find user 
                        List<User> users = usermanager.getSendersForConfig(Arrays.asList(ct.getconfigId()));
                        if (users.size() == 0) {
                            users = usermanager.getOrgUsersForConfig(Arrays.asList(ct.getconfigId()));
                        }

                        batchInfo.setuserId(users.get(0).getId());
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        statusId = 2;

                    } else if (transportList.size() > 1 && transports.size() > 1) {
                        //we loop though our delimiters for this type of fileExt
                        String delimiter = "";
                        Integer fileDelimiter = 0;
                        String fileLocation = "";
                        Integer userId = 0;
                        //get distinct delimiters
                        List<configurationTransport> delimList = configurationtransportmanager
                                .getDistinctDelimCharForFileExt(fileExt, transportMethodId);
                        List<configurationTransport> encodings = configurationtransportmanager
                                .getTransportEncoding(fileExt, transportMethodId);
                        //we reject file is multiple encodings/delimiters are found for extension type as we won't know how to decode it and read delimiter
                        if (encodings.size() != 1) {
                            batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                            statusId = 7;
                            errorId = 16;
                        } else {
                            encodingId = encodings.get(0).getEncodingId();
                            for (configurationTransport ctdelim : delimList) {
                                fileSystem dir = new fileSystem();
                                int delimCount = (Integer) dir.checkFileDelimiter(file, ctdelim.getDelimChar());
                                if (delimCount > 3) {
                                    delimiter = ctdelim.getDelimChar();
                                    fileDelimiter = ctdelim.getfileDelimiter();
                                    statusId = 2;
                                    fileLocation = ctdelim.getfileLocation();
                                    break;
                                }
                            }
                        }
                        // we don't have an error yet

                        if (errorId > 0) {
                            // some error detected from previous checks
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                        } else if (statusId != 2) {
                            //no vaild delimiter detected
                            statusId = 7;
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                            errorId = 15;
                        } else if (statusId == 2) {
                            encodingId = encodings.get(0).getEncodingId();
                            //we check to see if there is multi header row, if so, we reject because we don't know what header rows value to look for
                            List<configurationTransport> containsHeaderRowCount = configurationtransportmanager
                                    .getCountContainsHeaderRow(fileExt, transportMethodId);

                            if (containsHeaderRowCount.size() != 1) {
                                batchInfo.setuserId(
                                        usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                                statusId = 7;
                                errorId = 14;
                            } else {
                                List<Integer> totalConfigs = configurationtransportmanager
                                        .getConfigCount(fileExt, transportMethodId, fileDelimiter);

                                //set how many configs we have
                                if (totalConfigs.size() > 1) {
                                    configId = 0;
                                } else {
                                    configId = totalConfigs.get(0);
                                }

                                //get path
                                fileLocation = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getfileLocation();
                                fileSize = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getmaxFileSize();
                                List<User> users = usermanager.getSendersForConfig(totalConfigs);
                                if (users.size() == 0) {
                                    users = usermanager.getOrgUsersForConfig(totalConfigs);
                                }
                                userId = users.get(0).getId();
                                batchInfo.setContainsHeaderRow(
                                        containsHeaderRowCount.get(0).getContainsHeaderRow());
                                batchInfo.setDelimChar(delimiter);
                                batchInfo.setConfigId(configId);
                                batchInfo.setFileLocation(fileLocation);
                                outPath = fileSystem.setPath(fileLocation);
                                batchInfo.setOrgId(orgId);
                                newFileName = newFileName(outPath, fileName);
                                batchInfo.setoriginalFileName(newFileName);
                                batchInfo.setuserId(userId);
                                batchInfo.setEncodingId(encodingId);
                                batchId = (Integer) submitBatchUpload(batchInfo);
                            }
                        }
                    }
                    /** insert log**/
                    try {
                        //log user activity
                        UserActivity ua = new UserActivity();
                        ua.setUserId(0);
                        ua.setFeatureId(0);
                        ua.setAccessMethod("System");
                        ua.setActivity("System Uploaded File");
                        ua.setBatchUploadId(batchInfo.getId());
                        usermanager.insertUserLog(ua);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.err.println("moveFilesByPath - insert user log" + ex.toString());
                    }
                    //we encoded user's file if it is not
                    File newFile = new File(outPath + newFileName);
                    // now we move file
                    Path source = file.toPath();
                    Path target = newFile.toPath();

                    File archiveFile = new File(fileSystem.setPath(archivePath) + batchName
                            + newFileName.substring(newFileName.lastIndexOf(".")));
                    Path archive = archiveFile.toPath();
                    //we keep original file in archive folder
                    Files.copy(source, archive);

                    /**
                     * we check encoding here *
                     */
                    if (encodingId < 2) { //file is not encoded
                        String encodedOldFile = filemanager.encodeFileToBase64Binary(file);
                        filemanager.writeFile(newFile.getAbsolutePath(), encodedOldFile);
                        Files.delete(source);
                    } else {
                        Files.move(source, target);
                    }

                    if (statusId == 2) {
                        /**
                         * check file size if configId is 0 we go with the smallest file size *
                         */
                        long maxFileSize = fileSize * 1000000;
                        if (Files.size(target) > maxFileSize) {
                            statusId = 7;
                            errorId = 12;
                        }
                    }

                    if (statusId != 2) {
                        insertProcessingError(errorId, 0, batchId, null, null, null, null, false, false, "");
                    }

                    updateBatchStatus(batchId, statusId, "endDateTime");

                } catch (Exception exAtFile) {
                    exAtFile.printStackTrace();
                    System.err.println("moveFilesByPath " + exAtFile.toString());
                    try {
                        sendEmailToAdmin(
                                (exAtFile.toString() + "<br/>" + Arrays.toString(exAtFile.getStackTrace())),
                                "moveFilesByPath - at rename file to error ");
                        //we need to move that file out of the way
                        file.renameTo((new File(file.getAbsolutePath() + batchName + "_error")));
                    } catch (Exception ex1) {
                        ex1.printStackTrace();
                        System.err.println("moveFilesByPath " + ex1.getMessage());

                    }
                }
            }

        }

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            sendEmailToAdmin((ex.toString() + "<br/>" + Arrays.toString(ex.getStackTrace())),
                    "moveFilesByPath - issue with looping folder files");
        } catch (Exception ex1) {
            ex1.printStackTrace();
            System.err.println("moveFilesByPath " + ex1.getMessage());
        }
        return 1;
    }
    return sysErrors;
}