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.testeditor.fixture.swt.SwtBotFixture.java

/**
 * delete a given file or directory in the workspace
 * /*from   w  w w .  j  a  va 2s .  c o m*/
 * @param relTargetPath
 *            the workspace relative path of the source file or directory to
 *            delete (recursively in the later case)
 */
public void deleteInWorkspace(String relTargetPath) {
    File workspaceDir;
    try {
        workspaceDir = new File(getWorkspacePath());
    } catch (IOException e1) {
        String msg = "cannot find workspacePath";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }
    File target = new File(workspaceDir, relTargetPath);

    if (target.exists()) {
        if (target.isDirectory()) {
            deleteFolder(target);
        } else {
            try {
                Files.delete(target.toPath());
            } catch (IOException e) {
                String msg = "cannot delete file '" + target + "'";
                LOGGER.error(msg, e);
                throw new StopTestException(msg, e);
            }
        }
    }

}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Deletes folder recursively.//  w w  w . j a  v  a  2  s. c  o  m
 * 
 * @param target
 *            to be deleted.
 */
private void deleteFolder(File target) {
    List<File> files = Arrays.asList(target.listFiles());
    for (File file : files) {
        if (file.isFile()) {
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                String msg = "cannot delete file '" + target + "'";
                LOGGER.error(msg, e);
                throw new StopTestException(msg, e);
            }
        } else {
            deleteFolder(file);
        }
    }
    try {
        Files.delete(target.toPath());
    } catch (IOException e) {
        String msg = "cannot delete file '" + target + "'";
        LOGGER.error(msg, e);
        throw new StopTestException(msg, e);
    }
}

From source file:lu.fisch.moenagade.model.Project.java

public boolean removeEntity(Entity entity) {
    int answ = JOptionPane.showConfirmDialog(frame,
            "Are you sure to remove the entity \"" + entity.getName() + "\"", "Remove an entity",
            JOptionPane.YES_NO_OPTION);
    if (answ == JOptionPane.YES_OPTION) {
        try {/*ww w  .j ava2 s . co m*/
            Files.delete((new File(getDirectoryName() + System.getProperty("file.separator") + "bloxs"
                    + System.getProperty("file.separator") + "entities" + System.getProperty("file.separator")
                    + entity.getName() + ".bloxs")).toPath());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        entities.remove(entity.getName());
        refresh(new Change(null, -1, "delete.entity", entity, null));
        return true;
    }
    return false;
}

From source file:lu.fisch.moenagade.model.Project.java

public boolean removeWorld(World world) {
    int answ = JOptionPane.showConfirmDialog(frame,
            "Are you sure to remove the world \"" + world.getName() + "\"", "Remove a world",
            JOptionPane.YES_NO_OPTION);
    if (answ == JOptionPane.YES_OPTION) {
        try {/* w w w  .  j ava2 s. c o  m*/
            Files.delete((new File(getDirectoryName() + System.getProperty("file.separator") + "bloxs"
                    + System.getProperty("file.separator") + "worlds" + System.getProperty("file.separator")
                    + world.getName() + ".bloxs")).toPath());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        worlds.remove(world.getName());
        refresh(new Change(null, -1, "delete.world", world, null));
        return true;
    }
    return false;
}

From source file:lu.fisch.moenagade.model.Project.java

public boolean removeImage(ImageFile imageFile) {
    int answ = JOptionPane.showConfirmDialog(frame,
            "Are you sure to remove the image \"" + imageFile.getName() + "\"", "Remove an image",
            JOptionPane.YES_NO_OPTION);
    if (answ == JOptionPane.YES_OPTION) {
        try {//  www .  j  a v  a2  s  .  c  om
            Files.delete(imageFile.toPath());
            refresh(new Change(null, -1, "delete.image", imageFile, null));
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }

    }
    return false;
}

From source file:lu.fisch.moenagade.model.Project.java

public boolean removeSound(SoundFile soundFile) {
    int answ = JOptionPane.showConfirmDialog(frame,
            "Are you sure to remove the sound \"" + soundFile.getName() + "\"", "Remove a sound",
            JOptionPane.YES_NO_OPTION);
    if (answ == JOptionPane.YES_OPTION) {
        try {//from  w ww . j av  a 2  s .  co m
            Files.delete(soundFile.toPath());
            refresh(new Change(null, -1, "delete.sound", soundFile, null));
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }

    }
    return false;
}

From source file:org.roda.wui.api.controllers.BrowserHelper.java

public static void createOrUpdateAIPRepresentationPreservationMetadataFile(String aipId,
        String representationId, List<String> fileDirectoryPath, String fileId, InputStream is, boolean create)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException,
        ValidationException, AlreadyExistsException {
    Path file = null;//from w ww .j a v a  2s. c  om
    try {
        ModelService model = RodaCoreFactory.getModelService();
        file = Files.createTempFile("preservation", ".tmp");
        Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
        ContentPayload payload = new FSPathContentPayload(file);
        boolean notify = true;
        if (create) {
            model.createPreservationMetadata(PreservationMetadataType.FILE, aipId, representationId,
                    fileDirectoryPath, fileId, payload, notify);
        } else {
            PreservationMetadataType type = PreservationMetadataType.FILE;
            String id = IdUtils.getPreservationFileId(fileId);
            model.updatePreservationMetadata(id, type, aipId, representationId, fileDirectoryPath, fileId,
                    payload, notify);
        }
    } catch (IOException e) {
        throw new GenericException("Error creating or updating AIP representation preservation metadata file",
                e);
    } finally {
        if (FSUtils.exists(file)) {
            try {
                Files.delete(file);
            } catch (IOException e) {
                LOGGER.warn("Error while deleting temporary file", e);
            }
        }
    }
}

From source file:org.dcm4chee.proxy.forward.ForwardFiles.java

private Collection<ForwardTask> scanFiles(ProxyAEExtension proxyAEE, String calledAET, File[] files) {
    HashMap<String, ForwardTask> map = new HashMap<String, ForwardTask>(4);
    for (File file : files) {
        try {/*from   w  w  w  .  j  a  v  a  2s  . c o  m*/
            if (lock.tryLock(100, TimeUnit.MILLISECONDS)) {
                try {
                    if (file.exists()) {
                        String prevFilePath = file.getPath();
                        File snd = new File(prevFilePath + ".snd");
                        try {
                            Files.move(file.toPath(), snd.toPath(), StandardCopyOption.REPLACE_EXISTING);
                            LOG.debug("Successfully renamed {} to {}", prevFilePath, snd.getPath());
                            LOG.debug("Adding file {} to forward tasks ", snd.getPath());
                            addFileToFwdTaskMap(proxyAEE, calledAET, snd, map);
                            LOG.debug(
                                    "Successfully added file {} to forward tasks , proceeding with scheduled send",
                                    snd.getPath());
                        } catch (Exception e) {
                            LOG.error(
                                    "Error moving {} to {}. Skip file for now and try again on next scheduler run. - {}",
                                    prevFilePath, snd.getPath(), e);
                            if (!file.exists() && snd.exists())
                                if (snd.renameTo(file))
                                    LOG.debug("Rename {} to {}", snd.getPath(), file.getPath());
                                else
                                    LOG.debug("Error renaming {} to {}", snd.getPath(), file.getPath());
                            else if (snd.exists() && file.exists())
                                try {
                                    Files.delete(snd.toPath());
                                } catch (Exception e1) {
                                    LOG.error(
                                            "Unable to delete file {} after failed rename from  {} to {}  - {}",
                                            snd, prevFilePath, snd.getPath(), e1);
                                }
                        }
                    }
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            LOG.error("Error acquiring lock for file scan and rename {}", e);
        }
    }
    return map.values();
}

From source file:servlets.Samples_servlets.java

/**
 * *//from   w ww .j a  v  a2 s . c  om
 *
 * @param request
 * @param response
 * @throws IOException
 */
private void export_samples_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {
        DAO dao_instance = null;
        BioCondition biocondition = null;
        String tmpFile = "";
        Path tmpDir = null;

        try {
            String format = request.getParameter("format");
            if (format == null) {
                format = "json";
            }

            Map<String, Cookie> cookies = this.getCookies(request);

            String loggedUser, sessionToken;
            loggedUser = cookies.get("loggedUser").getValue();
            sessionToken = cookies.get("sessionToken").getValue();

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 Get THE ANALYSIS Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Biocondition");
            boolean loadRecursive = true;
            Object[] params = { loadRecursive };
            String biocondition_id = request.getParameter("biocondition_id");
            biocondition = (BioCondition) dao_instance.findByID(biocondition_id, params);

            tmpDir = Files.createTempDirectory(null);
            tmpFile = biocondition.export(tmpDir.toString(), format,
                    this.getServletContext().getRealPath("/data/templates"));

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "export_samples_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 3b CATCH ERROR. GO TO STEP 4
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                /**
                 * *******************************************************
                 * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4
                 * *******************************************************
                 */
                // reads input file from an absolute path
                File downloadFile = new File(tmpFile);
                try {
                    FileInputStream inStream = new FileInputStream(downloadFile);
                    // gets MIME type of the file
                    String mimeType = getServletContext().getMimeType(tmpFile);
                    if (mimeType == null) {
                        // set to binary type if MIME mapping not found
                        mimeType = "application/octet-stream";
                    }
                    response.setContentType(mimeType);
                    response.setHeader("Content-Disposition", "filename=\"" + downloadFile.getName() + "\"");

                    // obtains response's output stream
                    OutputStream outStream = response.getOutputStream();

                    byte[] buffer = new byte[4096];
                    int bytesRead = -1;

                    while ((bytesRead = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, bytesRead);
                    }

                    inStream.close();
                    outStream.close();
                } catch (Exception ex) {
                } finally {
                    if (downloadFile.exists()) {
                        downloadFile.delete();
                    }
                    if (tmpDir != null) {
                        Files.delete(tmpDir);
                    }
                }
            }
            /**
             * *******************************************************
             * STEP 4 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "export_samples_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.dcm4chee.proxy.forward.ForwardFiles.java

private static void deleteFile(Association as, File file) {
    try {//from   w w w.  j  ava 2  s.  c  o  m
        Files.delete(file.toPath());
        LOG.debug("{}: delete {}", as, file);
    } catch (Exception e) {
        LOG.debug("{}: failed to delete {} - {}", as, file, e);
    }

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