List of usage examples for java.nio.file Files delete
public static void delete(Path path) throws IOException
From source file:com.streamsets.pipeline.lib.io.FileContext.java
public void releaseReader(boolean inErrorDiscardReader) throws IOException { Utils.checkState(open, "FileContext is closed"); // update starting offsets for next invocation either cold (no reader) or hot (reader) boolean hasNext; try {/*from www.java 2 s .com*/ hasNext = reader != null && reader.hasNext(); } catch (IOException ex) { IOUtils.closeQuietly(reader); reader = null; hasNext = false; } boolean doneWithFile = !hasNext || inErrorDiscardReader; if (doneWithFile) { IOUtils.closeQuietly(reader); reader = null; // Using Long.MAX_VALUE to signal we reach the end of the file and next iteration should get the next file. setStartingCurrentFileName(currentFile); setStartingOffset(Long.MAX_VALUE); // If we failed to open the file in first place, it will be null and hence we won't do anything with it. if (currentFile == null) { return; } // File end event LiveFile file = currentFile.refresh(); if (file == null) { return; } if (inErrorDiscardReader) { LOG.warn("Processing file '{}' produced an error, skipping '{}' post processing on that file", file, postProcessing); eventPublisher.publish(new FileEvent(file, FileEvent.Action.ERROR)); } else { eventPublisher.publish(new FileEvent(file, FileEvent.Action.END)); switch (postProcessing) { case NONE: LOG.debug("File '{}' processing completed, post processing action 'NONE'", file); break; case DELETE: try { Files.delete(file.getPath()); LOG.debug("File '{}' processing completed, post processing action 'DELETED'", file); } catch (IOException ex) { throw new IOException(Utils.format("Could not delete '{}': {}", file, ex.toString()), ex); } break; case ARCHIVE: Path fileArchive = Paths.get(archiveDir, file.getPath().toString()); if (fileArchive == null) { throw new IOException("Could not find archive file"); } try { Files.createDirectories(fileArchive.getParent()); Files.move(file.getPath(), fileArchive); LOG.debug("File '{}' processing completed, post processing action 'ARCHIVED' as", file); } catch (IOException ex) { throw new IOException(Utils.format("Could not archive '{}': {}", file, ex.toString()), ex); } break; } } } else { setStartingCurrentFileName(currentFile); setStartingOffset(getReader().getOffset()); } }
From source file:org.carcv.web.beans.StorageBeanIT.java
/** * Test method for {@link org.carcv.web.beans.StorageBean#storeBatchToDatabase(java.util.List)}. * * @throws Exception//from w ww . j ava 2 s.c om */ @Test public void testStoreBatchToDatabase() throws Exception { Random r = new Random(); FileEntryTool tool = new FileEntryTool(); // prepare FileEntry[] arr = new FileEntry[r.nextInt(11)]; List<FileEntry> list = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { FileEntry f = tool.generate(); assertNotNull(f); arr[i] = f; list.add(i, f); } Arrays.sort(arr); Collections.sort(list); // store and get storageBean.storeBatchToDatabase(list); ArrayList<FileEntry> got = (ArrayList<FileEntry>) entryBean.getAll(); assertNotNull(got); assertEquals(list.size(), got.size()); for (int i = 0; i < list.size(); i++) { assertTrue(got.contains(list.get(i))); assertEquals(got.get(i), entryBean.findById(got.get(i).getId())); } // clean up entryBean.remove(list.toArray(arr)); for (FileEntry entry : arr) { for (FileCarImage fi : entry.getCarImages()) { Files.delete(fi.getFilepath()); } } tool.close(); }
From source file:com.spotify.scio.util.RemoteFileUtil.java
private Path downloadImpl(URI src) { try {//w w w . j av a 2s . c o m Path dst = getDestination(src); if (src.getScheme() == null || src.getScheme().equals("file")) { // Local URI Path srcPath = src.getScheme() == null ? Paths.get(src.toString()) : Paths.get(src); if (Files.isSymbolicLink(dst) && Files.readSymbolicLink(dst).equals(srcPath)) { LOG.info("URI {} already symlink-ed", src); } else { Files.createSymbolicLink(dst, srcPath); LOG.info("Symlink-ed {} to {}", src, dst); } } else { // Remote URI long srcSize = getRemoteSize(src); boolean shouldDownload = true; if (Files.exists(dst)) { long dstSize = Files.size(dst); if (srcSize == dstSize) { LOG.info("URI {} already downloaded", src); shouldDownload = false; } else { LOG.warn("Destination exists with wrong size. {} [{}B] -> {} [{}B]", src, srcSize, dst, dstSize); Files.delete(dst); } } if (shouldDownload) { copyToLocal(src, dst); LOG.info("Downloaded {} -> {} [{}B]", src, dst, srcSize); } } return dst; } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java
@Test(enabled = true, invocationCount = 128) public void encodeDecodeRandomFiles() throws IOException { final Path expectedPath = Files.createTempFile("test", null); getRuntime().addShutdownHook(new Thread(() -> { try {/*w w w .j a v a 2 s .c o m*/ Files.delete(expectedPath); } catch (final IOException ioe) { ioe.printStackTrace(System.err); } })); final byte[] array = new byte[1024]; final ByteBuffer buffer = ByteBuffer.wrap(array); try (final FileChannel decodedChannel = FileChannel.open(expectedPath, StandardOpenOption.WRITE)) { final int count = current().nextInt(128); for (int i = 0; i < count; i++) { current().nextBytes(array); decodedChannel.write(buffer); } decodedChannel.force(false); } encodeDecode(expectedPath); }
From source file:com.kakao.hbase.manager.command.ExportKeysTest.java
@Test public void testRegexAll() throws Exception { if (miniCluster) { String outputFile = "exportkeys_test.keys"; try {//w w w. j a va 2 s . com String splitPoint = "splitpoint"; splitTable(splitPoint.getBytes()); String tableName2 = createAdditionalTable(tableName + "2"); splitTable(tableName2, splitPoint.getBytes()); String[] argsParam = { "zookeeper", ".*", outputFile }; Args args = new ManagerArgs(argsParam); assertEquals("zookeeper", args.getZookeeperQuorum()); ExportKeys command = new ExportKeys(admin, args); waitForSplitting(2); waitForSplitting(tableName2, 2); command.run(); List<Triple<String, String, String>> results = new ArrayList<>(); for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) { String[] split = keys.split(ExportKeys.DELIMITER); results.add(new ImmutableTriple<>(split[0], split[1], split[2])); } assertEquals(4, results.size()); } finally { Files.delete(Paths.get(outputFile)); } } }
From source file:de.cebitec.readXplorer.util.GeneralUtils.java
/** * Deletes the given file and if existent also the corresponding ".bai" * index file./* w w w .j a va 2 s. c o m*/ * @param lastWorkFile the file to delete * @return true, if the file could be deleted, false otherwise * @throws IOException */ public static boolean deleteOldWorkFile(File lastWorkFile) throws IOException { boolean deleted = false; if (lastWorkFile.canWrite()) { try { Files.delete(lastWorkFile.toPath()); deleted = true; File indexFile = new File(lastWorkFile.getAbsolutePath().concat(Properties.BAM_INDEX_EXT)); if (indexFile.canWrite()) { Files.delete(indexFile.toPath()); } } catch (IOException ex) { throw new IOException(NbBundle.getMessage(GeneralUtils.class, "MSG_GeneralUtils.FileDeletionError", lastWorkFile.getAbsolutePath())); } } return deleted; }
From source file:com.oneops.util.SearchSenderTest.java
private void emptyRetryDir() { Path directory = Paths.get(retryDir); try {/*from w ww. ja va 2 s.c o m*/ Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return CONTINUE; } }); Files.createDirectories(directory); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.romeikat.datamessie.core.base.util.FileUtil.java
public synchronized File createTxtFilesAndZip(String filename, final Collection<? extends FileDto> fileDtos, final SXSSFWorkbook summaryWorkbook) { try {/*from ww w . jav a2s .c o m*/ filename = normalizeFilename(filename); // Create temporary directory final Path tempDir = Files.createTempDirectory(filename); // Create temporary files final List<Path> tempFiles = createTempFiles(tempDir, fileDtos); if (summaryWorkbook != null) { final Path tempSummary = createXlsxFile(tempDir, "Summary", summaryWorkbook); tempFiles.add(tempSummary); } // Create ZIP file final Path zipFile = createZipFile(exportDir, filename, tempFiles); // Delete temporary files for (final Path tempFile : tempFiles) { Files.delete(tempFile); } // Delete temporary directory Files.delete(tempDir); // Done return zipFile.toFile(); } catch (final Exception e) { LOG.error("Could not create ZIP file", e); return null; } }
From source file:nl.mpi.oai.harvester.control.FileSynchronization.java
/** * * Removes files based on list provided in file *//*from w w w . j ava 2 s. c o m*/ private static void delete(final Provider provider, final File file, final String dir) { Stream<String> fileStream = getAsStream(file); if (fileStream != null) { fileStream.forEach(l -> { Path path = Paths.get(dir + l); if (Files.exists(path)) { try { Files.delete(path); saveToHistoryFile(provider, path, Operation.DELETE); } catch (IOException e) { logger.error("Error while deleting " + path + " file: ", e); } } }); } }
From source file:org.transitime.applications.SchemaGenerator.java
/** * Gets rid of the unwanted drop table commands. These aren't needed because * the resulting script is intended only for creating a database, not for * deleting all the data and recreating the tables. * //from w w w . j a v a 2 s.c o m * @param outputFilename */ private void trimCruftFromFile(String outputFilename) { // Need to write to a temp file because if try to read and write // to same file things get quite confused. String tmpFileName = outputFilename + "_tmp"; BufferedReader reader = null; BufferedWriter writer = null; try { FileInputStream fis = new FileInputStream(outputFilename); reader = new BufferedReader(new InputStreamReader(fis)); FileOutputStream fos = new FileOutputStream(tmpFileName); writer = new BufferedWriter(new OutputStreamWriter(fos)); String line; while ((line = reader.readLine()) != null) { // Filter out "drop table" commands if (line.contains("drop table")) { // Read in following blank line line = reader.readLine(); // Continue to next line since filtering out drop table commands continue; } // Filter out "drop sequence" oracle commands if (line.contains("drop sequence")) { // Read in following blank line line = reader.readLine(); // Continue to next line since filtering out drop commands continue; } // Filter out the alter table commands where dropping a key or // a constraint if (line.contains("alter table")) { String nextLine = reader.readLine(); if (nextLine.contains("drop")) { // Need to continue reading until process a blank line while (reader.readLine().length() != 0) ; // Continue to next line since filtering out drop commands continue; } else { // It is an "alter table" command but not a "drop". // Therefore need to keep this command. Since read in // two lines need to handle this specially and then // continue writer.write(line); writer.write("\n"); writer.write(nextLine); writer.write("\n"); continue; } } // Line not being filtered so write it to the file writer.write(line); writer.write("\n"); } } catch (IOException e) { System.err.println("Could not trim cruft from file " + outputFilename + " . " + e.getMessage()); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { } } // Move the temp file to the original name try { Files.copy(new File(tmpFileName).toPath(), new File(outputFilename).toPath(), StandardCopyOption.REPLACE_EXISTING); Files.delete(new File(tmpFileName).toPath()); } catch (IOException e) { System.err.println("Could not rename file " + tmpFileName + " to " + outputFilename); } }