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.spotify.docker.UtilsTest.java

@Test
public void testSaveImage() throws Exception {
    final DockerClient dockerClient = mock(DockerClient.class);
    final Log log = mock(Log.class);
    final Path path = Files.createTempFile(IMAGE, ".tgz");
    final String imageDataLine = "TestDataForDockerImage";

    Mockito.doAnswer(new Answer<InputStream>() {
        @Override//from ww w.jav a  2s.c o  m
        public InputStream answer(InvocationOnMock invocation) throws Throwable {
            return new ReaderInputStream(new StringReader(imageDataLine));
        }
    }).when(dockerClient).save(IMAGE);

    try {
        Utils.saveImage(dockerClient, IMAGE, path, log);
        verify(dockerClient).save(eq(IMAGE));
    } finally {
        if (Files.exists(path)) {
            Files.delete(path);
        }
    }
}

From source file:cc.arduino.utils.network.FileDownloader.java

private void downloadFile(boolean noResume) throws InterruptedException {
    RandomAccessFile file = null;

    try {// w w w  . jav a  2s  . com
        // Open file and seek to the end of it
        file = new RandomAccessFile(outputFile, "rw");
        initialSize = file.length();

        if (noResume && initialSize > 0) {
            // delete file and restart downloading
            Files.delete(outputFile.toPath());
            initialSize = 0;
        }

        file.seek(initialSize);

        setStatus(Status.CONNECTING);

        Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
        if ("true".equals(System.getProperty("DEBUG"))) {
            System.err.println("Using proxy " + proxy);
        }

        HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
        connection.setRequestProperty("User-agent", userAgent);
        if (downloadUrl.getUserInfo() != null) {
            String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
            connection.setRequestProperty("Authorization", auth);
        }

        connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
        connection.setConnectTimeout(5000);
        setDownloaded(0);

        // Connect
        connection.connect();
        int resp = connection.getResponseCode();

        if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
            URL newUrl = new URL(connection.getHeaderField("Location"));

            proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());

            // open the new connnection again
            connection = (HttpURLConnection) newUrl.openConnection(proxy);
            connection.setRequestProperty("User-agent", userAgent);
            if (downloadUrl.getUserInfo() != null) {
                String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
                connection.setRequestProperty("Authorization", auth);
            }

            connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
            connection.setConnectTimeout(5000);

            connection.connect();
            resp = connection.getResponseCode();
        }

        if (resp < 200 || resp >= 300) {
            throw new IOException("Received invalid http status code from server: " + resp);
        }

        // Check for valid content length.
        long len = connection.getContentLength();
        if (len >= 0) {
            setDownloadSize(len);
        }
        setStatus(Status.DOWNLOADING);

        synchronized (this) {
            stream = connection.getInputStream();
        }
        byte buffer[] = new byte[10240];
        while (status == Status.DOWNLOADING) {
            int read = stream.read(buffer);
            if (read == -1)
                break;

            file.write(buffer, 0, read);
            setDownloaded(getDownloaded() + read);

            if (Thread.interrupted()) {
                file.close();
                throw new InterruptedException();
            }
        }

        if (getDownloadSize() != null) {
            if (getDownloaded() < getDownloadSize())
                throw new Exception("Incomplete download");
        }
        setStatus(Status.COMPLETE);
    } catch (InterruptedException e) {
        setStatus(Status.CANCELLED);
        // lets InterruptedException go up to the caller
        throw e;

    } catch (SocketTimeoutException e) {
        setStatus(Status.CONNECTION_TIMEOUT_ERROR);
        setError(e);

    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);

    } finally {
        IOUtils.closeQuietly(file);

        synchronized (this) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:io.personium.core.model.file.StreamingOutputForDavFile.java

/**
 * {@inheritDoc}//w  w  w .java  2s  . co m
 */
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
    if (null == hardLinkInput) {
        throw new WebApplicationException(new BinaryDataNotFoundException(hardLinkPath.toString()));
    }
    try {
        IOUtils.copy(hardLinkInput, output);
    } finally {
        IOUtils.closeQuietly(hardLinkInput);
        // ?????
        Files.delete(hardLinkPath);
    }
}

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

/**
 * This method is executed just before each test method
 * // w  w w  . java2  s .c om
 * @throws Throwable
 *         On any problem (test method will not be executed)
 */
@Before
public void setUp() throws Throwable {
    myLog.debug("entering");
    try {
        if (Files.exists(Testconstants.ROOT_DIR)) {
            Helper.deleteDirRecursive(Testconstants.ROOT_DIR);
        }

        /*
         * Preparing the test sandbox in current directory:
         * 
         * testsandbox
         *   +- orig
         *      +- sub1
         *         +- fileSub12.txt
         *   +- backup
         *      +- sub1
         *         +- fileSub1.txt
         *         +- fileSub12.txt
         *      +- sub2
         *         +- sub2sub1
         *            +- fileSub2Sub1.txt
         *         +- fileSub2.txt
         *      +- file1.txt
         *   +- evacuate
         *       <empty>
         */
        Files.createDirectory(Testconstants.ROOT_DIR);

        myOrigDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "orig");
        myOrigDirSub1 = Testconstants.createNewFolder(myOrigDir, "sub1");
        myOrigDirSub2 = Testconstants.createNewFolder(myOrigDir, "sub2");
        myOrigDirSub2Sub1 = Testconstants.createNewFolder(myOrigDirSub2, "sub2sub1");

        myOrigFile1 = Testconstants.createNewFile(myOrigDir, "file1.txt");
        myOrigFileSub1 = Testconstants.createNewFile(myOrigDirSub1, "fileSub1.txt");
        myOrigFileSub12 = Testconstants.createNewFile(myOrigDirSub1, "fileSub12.txt");
        myOrigFileSub2 = Testconstants.createNewFile(myOrigDirSub2, "fileSub2.txt");
        myOrigFileSub2Sub1 = Testconstants.createNewFile(myOrigDirSub2Sub1, "fileSub2Sub1.txt");

        myBackupDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "backup");
        FileUtils.copyFileToDirectory(myOrigFile1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub2.toFile(), myBackupDir.toFile());

        myEvacuateDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "evacuate");

        // delete some objects from orig dir:
        Helper.deleteDirRecursive(myOrigDirSub2);
        Files.delete(myOrigFile1);
        Files.delete(myOrigFileSub1);

        myDryRun = false;
        myMove = false;
        myOrigDirStr = myOrigDir.toString();
        myBackupDirStr = myBackupDir.toString();
        myEvacuateDirStr = myEvacuateDir.toString();

    } catch (Throwable t) {
        myLog.error("Throwable caught in setup", t);
        throw t;
    }
}

From source file:io.liveoak.testtools.AbstractTestCase.java

@AfterClass
public static void tearDownMongo() throws IOException {
    if (mongoLauncher != null) {
        mongoLauncher.stopMongo();/*  w  w w. java2  s.  com*/

        // wait for it to stop
        long start = System.currentTimeMillis();
        while (mongoLauncher.serverRunning(mongoHost, mongoPort, (e) -> {
            if (System.currentTimeMillis() - start > 120000)
                throw new RuntimeException(e);
        })) {

            if (System.currentTimeMillis() - start > 120000) {
                throw new RuntimeException("mongod process still seems to be running (2m timeout)");
            }
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted!");
            }
        }

        // now delete the data dir except log file
        Files.walkFileTree(new File(mongoLauncher.getDbPath()).toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!file.startsWith(mongoLauncher.getLogPath())) {
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }

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

        mongoLauncher = null;
    }
}

From source file:mpimp.assemblxweb.util.J5FileUtils.java

public static void deleteTuSubunitRelatedFiles(TuSubunit tuSubunit, AssemblXWebModel model) throws IOException {
    if (tuSubunit.getSequenceFileLoaded()) {
        // check first if the sequence file is not used by another subunit
        // as well
        List<TuSubunit> tuSubunits = tuSubunit.getParentTuUnit().getTuSubunits();
        int counter = 0;
        for (TuSubunit currentTuSubunit : tuSubunits) {
            if (currentTuSubunit.getSequenceFileName() != null
                    && currentTuSubunit.getSequenceFileName().equals(tuSubunit.getSequenceFileName())) {
                counter++;//w  ww. j av  a  2s . com
            }
        }
        if (counter > 1) {
            return; // sequence file is used more than once, so we must
                    // not delete it along with the subunit
        }
        String sequenceFilePathName = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName() + File.separator
                + AssemblXWebProperties.getInstance().getProperty("sequenceFileDirectory") + File.separator
                + tuSubunit.getSequenceFileName();
        Files.deleteIfExists(Paths.get(sequenceFilePathName));
        String sequencesDirPath = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName() + File.separator
                + AssemblXWebProperties.getInstance().getProperty("sequenceFileDirectory");
        File sequencesDir = new File(sequencesDirPath);
        if (sequencesDir.isDirectory() && sequencesDir.list().length == 0) {
            Files.delete(Paths.get(sequencesDirPath));
        }
        String tuDirectoryPath = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName();
        File tuDirectory = new File(tuDirectoryPath);
        if (tuDirectory.isDirectory() && tuDirectory.list().length == 0) {
            Files.delete(Paths.get(tuDirectoryPath));
        }
    }
}

From source file:ee.ria.xroad.signer.certmanager.FileBasedOcspCache.java

private static void delete(File file) {
    try {//from w w w .jav  a2s . co  m
        Files.delete(file.toPath());
    } catch (Exception e) {
        log.warn("Failed to delete {}: {}", file, e);
    }
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ReadableByteChannel expectedChannel) throws IOException {

    if (expectedChannel == null) {
        throw new NullPointerException("null expectedChannel");
    }/* w w w. j  a  va  2  s.  c o m*/

    final Path encodedPath = Files.createTempFile("test", null);
    getRuntime().addShutdownHook(new Thread(() -> {
        try {
            Files.delete(encodedPath);
        } catch (final IOException ioe) {
            ioe.printStackTrace(System.err);
        }
    }));
    final WritableByteChannel encodedChannel = FileChannel.open(encodedPath, StandardOpenOption.WRITE);

    final ByteBuffer decodedBuffer = ByteBuffer.allocate(128);
    final ByteBuffer encodedBuffer = ByteBuffer.allocate(decodedBuffer.capacity() << 1);

    while (expectedChannel.read(decodedBuffer) != -1) {
        decodedBuffer.flip(); // limit -> position; position -> zero
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact(); // position -> n  + 1; limit -> capacity
        decodedBuffer.compact();
    }

    decodedBuffer.flip();
    while (decodedBuffer.hasRemaining()) {
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact();
    }

    encodedBuffer.flip();
    while (encodedBuffer.hasRemaining()) {
        encodedChannel.write(encodedBuffer);
    }
}

From source file:org.kurento.room.test.AutodiscoveryKmsUrlTest.java

@Test
public void test() throws IOException {

    Path backup = null;//  www. ja va  2  s.  co  m

    Path configFile = Paths.get(StandardSystemProperty.USER_HOME.value(), ".kurento", "config.properties");

    System.setProperty("kms.uris", "[\"autodiscovery\"]");

    try {

        if (Files.exists(configFile)) {

            backup = configFile.getParent().resolve("config.properties.old");

            Files.move(configFile, backup);
            log.debug("Backed-up old config.properties");
        }

        Files.createDirectories(configFile.getParent());

        try (BufferedWriter writer = Files.newBufferedWriter(configFile, StandardCharsets.UTF_8)) {
            writer.write("kms.url.provider: " + TestKmsUrlProvider.class.getName() + "\r\n");
        }

        String contents = new String(Files.readAllBytes(configFile));
        log.debug("Config file contents:\n{}", contents);

        ConfigurableApplicationContext app = KurentoRoomServerApp.start(new String[] { "--server.port=7777" });

        NotificationRoomManager notifRoomManager = app.getBean(NotificationRoomManager.class);

        final RoomManager roomManager = notifRoomManager.getRoomManager();

        final KurentoClientSessionInfo kcSessionInfo = new DefaultKurentoClientSessionInfo("participantId",
                "roomName");

        new Thread(new Runnable() {
            @Override
            public void run() {
                roomManager.joinRoom("userName", "roomName", false, kcSessionInfo, "participantId");
            }
        }).start();

        try {
            Boolean result = queue.poll(10, TimeUnit.SECONDS);

            if (result == null) {
                fail("Event in KmsUrlProvider not called");
            } else {
                if (!result) {
                    fail("Test failed");
                }
            }

        } catch (InterruptedException e) {
            fail("KmsUrlProvider was not called");
        }

    } finally {

        Files.delete(configFile);

        if (backup != null) {
            Files.move(backup, configFile);
        }
    }
}

From source file:org.talend.dataprep.dataset.store.content.file.LocalFileContentStore.java

@Override
public void clear() {
    try {/*from  w w w. j  a v  a2  s . c o  m*/
        Path path = FileSystems.getDefault().getPath(storeLocation);
        if (!path.toFile().exists()) {
            return;
        }

        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // .nfs files are handled by the OS and can be deleted after the visitor started.
                // Exceptions on such files can be safely ignored
                if (file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    LOGGER.warn("unable to delete {}", file.getFileName(), exc);
                    return FileVisitResult.CONTINUE;
                }
                throw exc;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                // Skip NFS file content
                if (!file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                if (e == null) {
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed
                    throw e;
                }
            }
        });
    } catch (IOException e) {
        LOGGER.error("Unable to clear local data set content.", e);
        throw new TDPException(DataSetErrorCodes.UNABLE_TO_CLEAR_DATASETS, e);
    }
}