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:net.sf.jabref.gui.fieldeditors.FileListEditor.java

public FileListEditor(JabRefFrame frame, BibDatabaseContext databaseContext, String fieldName, String content,
        EntryEditor entryEditor) {//w  w  w.  j  av a  2  s .com
    this.frame = frame;
    this.databaseContext = databaseContext;
    this.fieldName = fieldName;
    this.entryEditor = entryEditor;
    label = new FieldNameLabel(fieldName);
    tableModel = new FileListTableModel();
    setText(content);
    setModel(tableModel);
    JScrollPane sPane = new JScrollPane(this);
    setTableHeader(null);
    addMouseListener(new TableClickListener());

    JButton add = new JButton(IconTheme.JabRefIcon.ADD_NOBOX.getSmallIcon());
    add.setToolTipText(Localization.lang("New file link (INSERT)"));
    JButton remove = new JButton(IconTheme.JabRefIcon.REMOVE_NOBOX.getSmallIcon());
    remove.setToolTipText(Localization.lang("Remove file link (DELETE)"));
    JButton up = new JButton(IconTheme.JabRefIcon.UP.getSmallIcon());

    JButton down = new JButton(IconTheme.JabRefIcon.DOWN.getSmallIcon());
    auto = new JButton(Localization.lang("Get fulltext"));
    JButton download = new JButton(Localization.lang("Download from URL"));
    add.setMargin(new Insets(0, 0, 0, 0));
    remove.setMargin(new Insets(0, 0, 0, 0));
    up.setMargin(new Insets(0, 0, 0, 0));
    down.setMargin(new Insets(0, 0, 0, 0));
    add.addActionListener(e -> addEntry());
    remove.addActionListener(e -> removeEntries());
    up.addActionListener(e -> moveEntry(-1));
    down.addActionListener(e -> moveEntry(1));
    auto.addActionListener(e -> autoSetLinks());
    download.addActionListener(e -> downloadFile());

    FormBuilder builder = FormBuilder.create()
            .layout(new FormLayout("fill:pref,1dlu,fill:pref,1dlu,fill:pref", "fill:pref,fill:pref"));
    builder.add(up).xy(1, 1);
    builder.add(add).xy(3, 1);
    builder.add(auto).xy(5, 1);
    builder.add(down).xy(1, 2);
    builder.add(remove).xy(3, 2);
    builder.add(download).xy(5, 2);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(sPane, BorderLayout.CENTER);
    panel.add(builder.getPanel(), BorderLayout.EAST);

    TransferHandler transferHandler = new FileListEditorTransferHandler(frame, entryEditor, null);
    setTransferHandler(transferHandler);
    panel.setTransferHandler(transferHandler);

    // Add an input/action pair for deleting entries:
    getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "delete");
    getActionMap().put("delete", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            int row = getSelectedRow();
            removeEntries();
            row = Math.min(row, getRowCount() - 1);
            if (row >= 0) {
                setRowSelectionInterval(row, row);
            }
        }
    });

    // Add an input/action pair for inserting an entry:
    getInputMap().put(KeyStroke.getKeyStroke("INSERT"), "insert");
    getActionMap().put("insert", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            addEntry();
        }
    });

    // Add input/action pair for moving an entry up:
    getInputMap().put(Globals.getKeyPrefs().getKey(KeyBinding.FILE_LIST_EDITOR_MOVE_ENTRY_UP), "move up");
    getActionMap().put("move up", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            moveEntry(-1);
        }
    });

    // Add input/action pair for moving an entry down:
    getInputMap().put(Globals.getKeyPrefs().getKey(KeyBinding.FILE_LIST_EDITOR_MOVE_ENTRY_DOWN), "move down");
    getActionMap().put("move down", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            moveEntry(1);
        }
    });

    JMenuItem openLink = new JMenuItem(Localization.lang("Open"));
    menu.add(openLink);
    openLink.addActionListener(e -> openSelectedFile());

    JMenuItem openFolder = new JMenuItem(Localization.lang("Open folder"));
    menu.add(openFolder);
    openFolder.addActionListener(e -> {
        int row = getSelectedRow();
        if (row >= 0) {
            FileListEntry entry = tableModel.getEntry(row);
            try {
                String path = "";
                // absolute path
                if (Paths.get(entry.link).isAbsolute()) {
                    path = Paths.get(entry.link).toString();
                } else {
                    // relative to file folder
                    for (String folder : databaseContext.getFileDirectory()) {
                        Path file = Paths.get(folder, entry.link);
                        if (Files.exists(file)) {
                            path = file.toString();
                            break;
                        }
                    }
                }
                if (!path.isEmpty()) {
                    JabRefDesktop.openFolderAndSelectFile(path);
                } else {
                    JOptionPane.showMessageDialog(frame, Localization.lang("File not found"),
                            Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
                }
            } catch (IOException ex) {
                LOGGER.debug("Cannot open folder", ex);
            }
        }
    });

    JMenuItem rename = new JMenuItem(Localization.lang("Move/Rename file"));
    menu.add(rename);
    rename.addActionListener(new MoveFileAction(frame, entryEditor, this, false));

    JMenuItem moveToFileDir = new JMenuItem(Localization.lang("Move file to file directory"));
    menu.add(moveToFileDir);
    moveToFileDir.addActionListener(new MoveFileAction(frame, entryEditor, this, true));

    JMenuItem deleteFile = new JMenuItem(Localization.lang("Delete local file"));
    menu.add(deleteFile);
    deleteFile.addActionListener(e -> {
        int row = getSelectedRow();
        // no selection
        if (row != -1) {

            FileListEntry entry = tableModel.getEntry(row);
            // null if file does not exist
            Optional<File> file = FileUtil.expandFilename(databaseContext, entry.link);

            // transactional delete and unlink
            try {
                if (file.isPresent()) {
                    Files.delete(file.get().toPath());
                }
                removeEntries();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(frame, Localization.lang("File permission error"),
                        Localization.lang("Cannot delete file"), JOptionPane.ERROR_MESSAGE);
                LOGGER.warn("File permission error while deleting: " + entry.link, ex);
            }
        }
    });
    adjustColumnWidth();
}

From source file:business.services.FileService.java

public void removeAttachment(File attachment) {
    fileRepository.delete(attachment);/*from   ww w  .ja  va 2  s .co  m*/
    Path path = fileSystem.getPath(uploadPath, attachment.getFilename());
    try {
        Files.delete(path);
    } catch (IOException e) {
        log.error(e);
        throw new FileDeleteError();
    }
}

From source file:dk.dma.msiproxy.common.provider.AbstractProviderService.java

/**
 * May be called periodically to clean up the message repo folder associated
 * with the provider.//from ww w  . j  av a2s . c o m
 * <p>
 * The procedure will determine which repository message ID's are still active.
 * and delete folders associated with messages ID's that are not active anymore.
 */
public void cleanUpMessageRepoFolder() {

    long t0 = System.currentTimeMillis();

    // Compute the ID's for message repository folders to keep
    Set<Integer> ids = computeReferencedMessageIds(messages);

    // Build a lookup map of all the paths that ara still active
    Set<Path> paths = new HashSet<>();
    ids.forEach(id -> {
        try {
            Path path = getMessageRepoFolder(id);
            // Add the path and the hashed sub-folders above it
            paths.add(path);
            paths.add(path.getParent());
            paths.add(path.getParent().getParent());
        } catch (IOException e) {
            log.error("Failed computing " + getProviderId() + "  message repo paths for id " + id + ": "
                    + e.getMessage());
        }
    });

    // Scan all sub-folders and delete those
    Path messageRepoRoot = getRepositoryService().getRepoRoot().resolve(MESSAGE_REPO_ROOT_FOLDER)
            .resolve(getProviderId());
    paths.add(messageRepoRoot);

    try {
        Files.walkFileTree(messageRepoRoot, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!paths.contains(dir)) {
                    log.info("Deleting message repo directory :" + dir);
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!paths.contains(file.getParent())) {
                    log.info("Deleting message repo file      :" + file);
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Failed cleaning up " + getProviderId() + " message repo: " + e.getMessage());
    }

    log.info(String.format("Cleaned up %s message repo in %d ms", getProviderId(),
            System.currentTimeMillis() - t0));
}

From source file:org.kalypso.kalypsomodel1d2d.conv.results.ResultMeta1d2dHelper.java

private static void deleteFileOrDirectory(final File lDir) {
    try {/* www .  j av  a 2s  . c o m*/
        if (lDir.isDirectory())
            FileUtils.deleteDirectory(lDir);
        else if (lDir.isFile())
            Files.delete(lDir.toPath());
    } catch (final IOException e1) {
        e1.printStackTrace();
    }
}

From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java

public void saveCookies() throws IOException {
    if (cookiesPath != null) {
        log.info("Save Cookies");
        if (Files.exists(cookiesPath)) {
            Files.delete(cookiesPath);
        }//ww  w . ja v a2 s .  c o m
        try (Writer w = Files.newBufferedWriter(cookiesPath, Charset.defaultCharset())) {
            w.write(JSONValue.toJSONString(con.request().cookies()));
        }
    }
}

From source file:jenkins.plugins.pbs.tasks.Qsub.java

private boolean loopSeek(String jobId) {
    boolean toReturn = false;
    while (true) {
        CommandOutput cmd = PBS.traceJob(jobId, numberOfDays);

        final String out = cmd.getOutput();
        // String err = cmd.getError();

        // listener.getLogger().println(out);
        // listener.getLogger().println("----");
        Matcher matcher = JOB_STATUS_REGEX.matcher(out.toString());
        if (matcher.find()) {
            String state = null;// w w  w  . j  a v a 2  s  .c o m
            if (matcher.groupCount() > 2) {
                state = matcher.group(3);
            }
            if (StringUtils.isBlank(state)) {
                state = matcher.group(1);
            }
            listener.getLogger().println("Found job state " + state);
            if ("COMPLETE".equals(state)) {
                // Now we look for the status
                matcher = JOB_SUBSTATUS_REGEX.matcher(out.toString());
                if (matcher.find()) {
                    state = matcher.group(1);
                    listener.getLogger().println("Found run job status of " + state);
                    listener.getLogger().println("---- Remote job output log ----");

                    InputStream outFile = null;
                    try {
                        outFile = Files.newInputStream(Paths.get(this.executionDirectory, "out"));
                        this.outputFileToLogger(outFile);
                    } catch (IOException e) {
                        listener.getLogger().println("ERROR: CANNOT PRINT OUT OUTPUT LOG - " + e.getMessage());
                        e.printStackTrace(listener.getLogger());
                    } finally {
                        IOUtils.closeQuietly(outFile);
                    }

                    listener.getLogger().println("---- End of remote job output log ----");
                    listener.getLogger().println("---- Remote job error log ----");
                    outFile = null;
                    try {
                        outFile = Files.newInputStream(Paths.get(this.executionDirectory, "err"));
                        this.outputFileToLogger(outFile);
                    } catch (IOException e) {
                        listener.getLogger().println("ERROR: CANNOT PRINT OUT ERROR LOG - " + e.getMessage());
                        e.printStackTrace(listener.getLogger());
                    } finally {
                        IOUtils.closeQuietly(outFile);
                    }
                    listener.getLogger().println("---- End of remote job error log ----");

                    // Return error code of the sub job
                    toReturn = "0".equals(state);
                    break;
                }
            }
            break;
        }
        try {
            // listener.getLogger().println("Sleeping for " + span + "ms");
            Thread.sleep(span);
        } catch (InterruptedException e) {
            e.printStackTrace(listener.getLogger());
        }
    }
    // We now know what to return but we can destroy the directory
    try {
        Files.delete(Paths.get(this.executionDirectory, "out"));
        Files.delete(Paths.get(this.executionDirectory, "err"));
    } catch (IOException e) {
        // Ignore
        listener.getLogger().println("Warning: Cannot remove log and/or error files");
        e.printStackTrace(listener.getLogger());
    }
    try {
        Files.delete(Paths.get(this.executionDirectory, "script"));
        Files.delete(Paths.get(this.executionDirectory));
    } catch (IOException e) {
        // Ignore
        listener.getLogger().println("Warning: Cannot remove script and work directory");
        e.printStackTrace(listener.getLogger());
    }
    return toReturn;
}

From source file:org.dihedron.webmvc.ActionContext.java

/**
 * Cleans up the internal status of the {@code ActionContext} in order to
 * avoid memory leaks due to persisting objects stored in the per-thread
 * local storage; afterwards it removes the thread local entry altogether,
 * so the application server does not complain about left-over data in TLS
 * when re-deploying the application (see Tomcat memory leak detection
 * feature).//from  w  w w.j a v a 2s  . c  o  m
 */
static void unbindContext() {
    logger.trace("removing action context for thread {}", Thread.currentThread().getId());
    getContext().filter = null;
    getContext().request = null;
    getContext().response = null;
    getContext().configuration = null;
    getContext().server = null;
    // remove all files if this is a multipart/form-data request, because
    // the file tracker does not seem to work as expected
    if (isMultiPartRequest()) {
        for (Entry<String, FileItem> entry : getContext().parts.entrySet()) {
            if (!entry.getValue().isFormField() && !entry.getValue().isInMemory()) {
                File file = ((DiskFileItem) entry.getValue()).getStoreLocation();
                try {
                    logger.trace("removing uploaded file '{}' from disk...", file.getAbsolutePath());
                    Files.delete(file.toPath());
                    logger.trace("... file deleted");
                } catch (IOException e) {
                    logger.trace("... error deleting file", e);
                }
            }
        }
    }
    getContext().parts = null;

    //      if(getContext().parts != null) {
    //         for(Entry<String, FileItem> entry : getContext().parts.entrySet()) {
    //            FileItem part = entry.getValue();
    //            if(!part.isFormField() && !part.isInMemory()) {
    //               logger.trace("releasing on-disk uploaded file '{}'", part.getFieldName());
    //               
    //            }
    //         }
    //      }
    context.remove();
}

From source file:com.clust4j.algo.KMeansTests.java

@Test
@Override/*from ww  w .jav a2 s  .  co m*/
public void testSerialization() throws IOException, ClassNotFoundException {
    KMeans km = new KMeans(data_, new KMeansParameters(3).setVerbose(true)).fit();
    System.out.println();

    final double c = km.getTSS();
    km.saveObject(new FileOutputStream(TestSuite.tmpSerPath));
    assertTrue(TestSuite.file.exists());

    KMeans km2 = (KMeans) KMeans.loadObject(new FileInputStream(TestSuite.tmpSerPath));
    assertTrue(km2.getTSS() == c);
    assertTrue(km.equals(km2));
    Files.delete(TestSuite.path);
}

From source file:company.gonapps.loghut.dao.PostDao.java

public void deleteCompression(PostDto post) throws IOException {
    rrwl.writeLock().lock();//ww w.  ja  v a 2s  .c o  m
    try {
        Files.delete(Paths.get(getPostPathString(post) + ".gz"));
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:nl.mvdr.umvc3replayanalyser.controller.ReplaySaver.java

/**
 * Edits a replay./*from  w  w  w  .  jav a  2s . c o m*/
 * 
 * @param oldReplay
 *            replay to be edited
 * @param newGame
 *            game, containing the new replay details to be used
 * @return new replay
 * @throws IOException
 *             in case saving the new replay fails
 */
Replay editReplay(Replay oldReplay, Game newGame) throws IOException {
    Replay result;
    if (oldReplay.getGame().equals(newGame)) {
        log.info("Replay remains unchanged.");
        result = oldReplay;
    } else {
        String oldBaseFilename = oldReplay.getGame().getBaseFilename(oldReplay.getCreationTime());

        String videoFilePath = FilenameUtils.normalize(this.configuration.getDataDirectory().getAbsolutePath()
                + FileUtils.SEPARATOR + oldReplay.getVideoLocation());
        File videoFile = new File(videoFilePath);
        Date creationTime = new Date(videoFile.lastModified());
        String newBaseFilename = newGame.getBaseFilename(creationTime);

        String newPreviewImageFileLocation;
        if (this.configuration.isSavePreviewImageToDataDirectory()) {
            // Move preview image.
            String oldPreviewImageFileLocation = oldReplay.getPreviewImageLocation();
            if (oldPreviewImageFileLocation.startsWith(FILE_URL_PREFIX)) {
                oldPreviewImageFileLocation = oldPreviewImageFileLocation.substring(FILE_URL_PREFIX.length());
            }
            File oldPreviewImageFile = new File(oldPreviewImageFileLocation);
            String previewImageExtension;
            int index = oldPreviewImageFileLocation.lastIndexOf('.');
            if (0 < index) {
                previewImageExtension = oldPreviewImageFileLocation.substring(index).toLowerCase();
            } else {
                // No extension.
                previewImageExtension = "";
            }
            File previewImageFile = new File(configuration.getDataDirectoryPath() + FileUtils.SEPARATOR
                    + newBaseFilename + previewImageExtension);

            // Note that move will fail with an IOException if previewImageFile aleady exists, but that it will
            // succeed if the old and new paths are the same.
            Files.move(oldPreviewImageFile.toPath(), previewImageFile.toPath());
            newPreviewImageFileLocation = FILE_URL_PREFIX + previewImageFile.getAbsolutePath();
            log.info(
                    String.format("Moved preview image from %s to %s.", oldPreviewImageFile, previewImageFile));
        } else {
            // Leave preview image wherever it is.
            newPreviewImageFileLocation = oldReplay.getPreviewImageLocation();
        }

        // Delete the old replay file.
        File oldReplayFile = new File(configuration.getDataDirectoryPath() + FileUtils.SEPARATOR
                + oldBaseFilename + REPLAY_EXTENSION);
        Files.delete(oldReplayFile.toPath());
        log.info(String.format("Deleted old replay file: %s.", oldReplayFile));

        result = saveReplay(videoFile, newGame, newPreviewImageFileLocation);
    }
    return result;
}