List of usage examples for java.nio.file Files delete
public static void delete(Path path) throws IOException
From source file:com.spectralogic.ds3client.helpers.FileSystemHelper_Test.java
@Test public void testObjectsFitBucketWithPathNotDirectory() throws IOException { final int maxNumBlockAllocationRetries = 1; final int maxNumObjectTransferAttempts = 1; final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(client, maxNumBlockAllocationRetries, maxNumObjectTransferAttempts); final Path textFile = Files.createFile(Paths.get("Gracie.txt")); try {/*from ww w. j a v a2 s . c om*/ final ObjectStorageSpaceVerificationResult result = ds3ClientHelpers .objectsFromBucketWillFitInDirectory("bad bucket name", Arrays.asList(new String[] {}), textFile); assertEquals(ObjectStorageSpaceVerificationResult.VerificationStatus.PathIsNotADirectory, result.getVerificationStatus()); assertEquals(0, result.getRequiredSpace()); assertEquals(0, result.getAvailableSpace()); assertFalse(result.containsSufficientSpace()); assertNull(result.getIoException()); } finally { Files.delete(textFile); } }
From source file:org.polymap.service.fs.providers.fs.FsContentProvider.java
public void delete(FsFolder folder) throws IOException { Files.delete(folder.getDir().toPath()); getSite().invalidateFolder(getSite().getFolder(folder.getParentPath())); }
From source file:org.panbox.desktop.common.vfs.backend.generic.GenericAPIIntegration.java
@Override public void deleteFile(String serverPath) throws CSPIOException { try {/*from w ww . j a va 2s .c om*/ Files.delete(Paths.get(serverPath)); } catch (IOException e) { throw new CSPIOException(e); } }
From source file:org.commonjava.maven.ext.cli.CliTest.java
@Test public void checkLocalRepositoryWithDefaultsAndModifiedUserSettings() throws Exception { boolean restore = false; Path source = Paths.get( System.getProperty("user.home") + File.separatorChar + ".m2" + File.separatorChar + "settings.xml"); Path backup = Paths.get(source.toString() + '.' + UUID.randomUUID().toString()); Path tmpSettings = Paths.get(getClass().getResource("/settings-test.xml").getFile()); try {/*from w w w . j a v a2s . com*/ if (source.toFile().exists()) { System.out.println("Backing up settings.xml to " + backup); restore = true; Files.move(source, backup, StandardCopyOption.ATOMIC_MOVE); } Files.copy(tmpSettings, source); Cli c = new Cli(); executeMethod(c, "run", new Object[] { new String[] {} }); ManipulationSession session = (ManipulationSession) FieldUtils.readField(c, "session", true); MavenSession ms = (MavenSession) FieldUtils.readField(session, "mavenSession", true); assertTrue(ms.getRequest().getLocalRepository().getBasedir() .equals(ms.getRequest().getLocalRepositoryPath().toString())); assertTrue(ms.getLocalRepository().getBasedir() .equals(System.getProperty("user.home") + File.separatorChar + ".m2-mead-test")); } finally { if (restore) { Files.move(backup, source, StandardCopyOption.ATOMIC_MOVE); } else { Files.delete(source); } } }
From source file:de.joinout.criztovyl.tools.directory.DirectorySync.java
/** * Removes all deleted files.//from w w w . j a va2 s .c om * @param force whether files should be deleted if base directory is empty. */ public void removeDeletedFiles(boolean force) { if (getCurrentList().isEmpty() && !force) { logger.warn("Not removing any files, base diretory is empty."); return; } //Iterate over files for (Path path : getDeletedFiles(false)) { //Make absolute path = getPreviousList().getDirectory().append(path); //Check if path needed to delete is a directory if (path.getFile().isDirectory()) try { //Try to delete directory recursively. if (logger.isInfoEnabled()) logger.info("Deleting {}", path); FileUtils.deleteDirectory(path.getFile()); if (logger.isInfoEnabled()) logger.info("Deleted."); } catch (IOException e) { //Catch general IOException. if (logger.isWarnEnabled()) logger.warn("There was an IOException while deleting the disappeared directory {}: {}", path, e.toString()); if (logger.isDebugEnabled()) logger.debug("IOException.", e); } else try { //Try to delete file, using NIO to get an exception whether something went wrong. if (logger.isInfoEnabled()) logger.info("Deleting {}", path); Files.delete(path.getNIOPath()); if (logger.isInfoEnabled()) logger.info("Deleted."); } catch (NoSuchFileException e) { //Catch NoSuchFileException (NIO FileNotFoundException), file may has been deleted by an earlier if (logger.isDebugEnabled()) logger.debug("File {} not found, may be already deleted?", path); } catch (IOException e) { if (logger.isWarnEnabled()) logger.warn("There was an IOException while deleting the disappeared directory {}: {}", path, e.toString()); if (logger.isDebugEnabled()) logger.debug("IOException.", e); } } }
From source file:org.carcv.web.beans.StorageBeanIT.java
/** * Test method for {@link org.carcv.web.beans.StorageBean#storeToDirectory(java.io.InputStream, String, Path)}. * * @throws Exception/*www . j ava 2s .c om*/ */ @Test public void testStoreToDirectory() throws Exception { FileEntryTool tool = new FileEntryTool(); InputStream is1 = getClass().getResourceAsStream("/img/skoda_oct.jpg"); InputStream is2 = getClass().getResourceAsStream("/img/test_041.jpg"); Path p1 = Paths.get("/tmp", "storageImage1-" + System.currentTimeMillis() + ".jpg"); Path p2 = Paths.get("/tmp", "storageImage2-" + System.currentTimeMillis() + ".jpg"); Files.copy(is1, p1); Files.copy(is2, p2); FileEntry f = tool.generate(p1, p2); assertFileEntry(f); assertNotNull(f); Path original = f.getCarImages().get(0).getFilepath(); assertNotNull(original); assertTrue(Files.exists(original)); // store String fileName = "test" + f.hashCode() + ".jpg"; storageBean.storeToDirectory(Files.newInputStream(original), fileName, Paths.get("/tmp")); Path newPath = Paths.get("/tmp", fileName); assertNotNull(newPath); assertTrue(Files.exists(newPath)); assertTrue(FileUtils.contentEquals(newPath.toFile(), original.toFile())); Files.delete(p1); Files.delete(p2); tool.close(); }
From source file:divconq.tool.Updater.java
static public boolean tryUpdate() { @SuppressWarnings("resource") final Scanner scan = new Scanner(System.in); FuncResult<RecordStruct> ldres = Updater.loadDeployed(); if (ldres.hasErrors()) { System.out.println("Error reading deployed.json file: " + ldres.getMessage()); return false; }//from w w w. j ava2s .c o m RecordStruct deployed = ldres.getResult(); String ver = deployed.getFieldAsString("Version"); String packfolder = deployed.getFieldAsString("PackageFolder"); String packprefix = deployed.getFieldAsString("PackagePrefix"); if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) { System.out.println("Error reading deployed.json file: Missing Version or PackageFolder"); return false; } if (StringUtil.isEmpty(packprefix)) packprefix = "DivConq"; System.out.println("Current Version: " + ver); Path packpath = Paths.get(packfolder); if (!Files.exists(packpath) || !Files.isDirectory(packpath)) { System.out.println("Error reading PackageFolder - it may not exist or is not a folder."); return false; } File pp = packpath.toFile(); RecordStruct deployment = null; File matchpack = null; for (File f : pp.listFiles()) { if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip")) continue; System.out.println("Checking: " + f.getName()); // if not a match before, clear this deployment = null; try { ZipFile zf = new ZipFile(f); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.getName().equals("deployment.json")) { //System.out.println("crc: " + entry.getCrc()); FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry)); if (pres.hasErrors()) { System.out.println("Error reading deployment.json file"); break; } deployment = (RecordStruct) pres.getResult(); break; } } zf.close(); } catch (IOException x) { System.out.println("Error reading deployment.json file: " + x); } if (deployment != null) { String fndver = deployment.getFieldAsString("Version"); String fnddependson = deployment.getFieldAsString("DependsOn"); if (ver.equals(fnddependson)) { System.out.println("Found update: " + fndver); matchpack = f; break; } } } if ((matchpack == null) || (deployment == null)) { System.out.println("No updates found!"); return false; } String fndver = deployment.getFieldAsString("Version"); String umsg = deployment.getFieldAsString("UpdateMessage"); if (StringUtil.isNotEmpty(umsg)) { System.out.println("========================================================================"); System.out.println(umsg); System.out.println("========================================================================"); } System.out.println(); System.out.println("Do you want to install? (y/n)"); System.out.println(); String p = scan.nextLine().toLowerCase(); if (!p.equals("y")) return false; System.out.println(); System.out.println("Intalling: " + fndver); Set<String> ignorepaths = new HashSet<>(); ListStruct iplist = deployment.getFieldAsList("IgnorePaths"); if (iplist != null) { for (Struct df : iplist.getItems()) ignorepaths.add(df.toString()); } ListStruct dflist = deployment.getFieldAsList("DeleteFiles"); // deleting if (dflist != null) { for (Struct df : dflist.getItems()) { Path delpath = Paths.get(".", df.toString()); if (Files.exists(delpath)) { System.out.println("Deleting: " + delpath.toAbsolutePath()); try { Files.delete(delpath); } catch (IOException x) { System.out.println("Unable to Delete: " + x); } } } } // copying updates System.out.println("Checking for updated files: "); try { @SuppressWarnings("resource") ZipFile zf = new ZipFile(matchpack); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String entryname = entry.getName().replace('\\', '/'); boolean xfnd = false; for (String exculde : ignorepaths) if (entryname.startsWith(exculde)) { xfnd = true; break; } if (xfnd) continue; System.out.print("."); Path localpath = Paths.get(".", entryname); if (entry.isDirectory()) { if (!Files.exists(localpath)) Files.createDirectories(localpath); } else { boolean hashmatch = false; if (Files.exists(localpath)) { String local = null; String update = null; try (InputStream lin = Files.newInputStream(localpath)) { local = HashUtil.getMd5(lin); } try (InputStream uin = zf.getInputStream(entry)) { update = HashUtil.getMd5(uin); } hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update) && local.equals(update)); } if (!hashmatch) { System.out.print("[" + entryname + "]"); try (InputStream uin = zf.getInputStream(entry)) { Files.createDirectories(localpath.getParent()); Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception x) { System.out.println("Error updating: " + entryname + " - " + x); return false; } } } } zf.close(); } catch (IOException x) { System.out.println("Error reading update package: " + x); } // updating local config deployed.setField("Version", fndver); OperationResult svres = Updater.saveDeployed(deployed); if (svres.hasErrors()) { System.out.println("Intalled: " + fndver + " but could not update deployed.json. Repair the file before continuing.\nError: " + svres.getMessage()); return false; } System.out.println("Intalled: " + fndver); return true; }
From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java
@Override public final File archiveFile(File file) throws QueueFileException { switch (getFileStatus(file)) { case NON_EXISTENT: throw new QueueFileException("File or symlink " + file + " no longer exists"); case CAPTURED_FILE: case CAPTURED_SYMLINK: break;//from w w w . j a v a2 s.c o m case BROKEN_CAPTURED_SYMLINK: throw new QueueFileException("Symlink target for " + file + " no longer exists"); default: throw new QueueFileException("File or symlink " + file + " is not in the queue"); } File dest = new File(archiveDirectory, file.getName()); if (dest.exists()) { throw new QueueFileException("Archived file " + dest + " already exists"); } if (Files.isSymbolicLink(file.toPath())) { dest = copyFile(file, dest, "archive"); try { Files.delete(file.toPath()); } catch (IOException ex) { throw new QueueFileException("Could not remove symlink " + file); } } else { if (!file.renameTo(dest)) { throw new QueueFileException("File " + file + " could not be renamed to " + dest); } } log.info("File " + file + " archived as " + dest); return dest; }
From source file:ca.polymtl.dorsal.libdelorean.statedump.Statedump.java
/** * Save this statedump at the given location. * * @param parentPath//from w w w . ja va 2 s .com * The location where to save the statedump file, usually in or * close to its corresponding trace. It will be put under a Trace * Compass-specific sub-directory. * @param ssid * The state system ID of the state system we are saving. This * will be used for restoration. * @throws IOException * If there are problems creating or writing to the target * directory */ public void dumpState(Path parentPath, String ssid) throws IOException { /* Create directory if it does not exist */ Path sdPath = parentPath.resolve(STATEDUMP_DIRECTORY); if (!Files.exists(sdPath)) { Files.createDirectory(sdPath); } /* Create state dump file */ String fileName = ssid + FILE_SUFFIX; Path filePath = sdPath.resolve(fileName); if (Files.exists(filePath)) { Files.delete(filePath); } Files.createFile(filePath); JSONObject root = new JSONObject(); try (Writer bw = Files.newBufferedWriter(filePath, Charsets.UTF_8)) { /* Create the root object */ root.put(Serialization.FORMAT_VERSION_KEY, STATEDUMP_FORMAT_VERSION); root.put(Serialization.ID_KEY, ssid); root.put(Serialization.STATEDUMP_VERSION_KEY, getVersion()); /* Create the root state node */ JSONObject rootNode = new JSONObject(); rootNode.put(Serialization.CHILDREN_KEY, new JSONObject()); root.put(Serialization.STATE_KEY, rootNode); /* Insert all the paths, types, and values */ for (int i = 0; i < getAttributes().size(); i++) { String[] attribute = getAttributes().get(i); StateValue sv = getStates().get(i); Serialization.insertFrom(rootNode, attribute, 0, sv); } bw.write(root.toString(2)); } catch (JSONException e) { /* * This should never happen. Any JSON exception means that there's a * bug in this code. */ throw new IllegalStateException(e); } }
From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java
private void processArchive(final Path zipFile, final int batchSize) throws IOException { try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipFile, null)) { final List<BookEntry> bookEntries = new ArrayList<>(); Path root = zipFileSystem.getPath("/"); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override/*from w w w . j a v a2 s.c om*/ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.toString().contains("__MACOSX")) { return FileVisitResult.SKIP_SUBTREE; } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) { BookEntry bookEntry = new BookEntry().setUploader("admin"); for (Path path : directoryStream) { if (!Files.isDirectory(path)) { if (path.toString().contains(".opf")) { bookEntry = parseOPF(path, bookEntry); } if (path.toString().contains(".mobi")) { bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI"); } if (path.toString().contains(".epub")) { bookEntry.setEpub(Files.readAllBytes(path)); } if (path.toString().contains(".jpg")) { bookEntry.setCover(Files.readAllBytes(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200) .toOutputStream(output); bookEntry.setThumbnail(output.toByteArray()); bookEntry.setThumbnailGenerated("done"); } } } if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) { bookEntries.add(bookEntry); if (bookEntries.size() > batchSize) { logger.info("Adding " + bookEntries.size() + " Books..."); try { solrHandler.addBeans(bookEntries); } catch (SolrServerException ex) { logger.error(ex, ex); } bookEntries.clear(); } } } catch (IOException ex) { logger.error(ex, ex); } return super.preVisitDirectory(dir, attrs); } }); try { if (!bookEntries.isEmpty()) { logger.info("Adding " + bookEntries.size() + " Books..."); solrHandler.addBeans(bookEntries); } } catch (SolrServerException ex) { logger.error(ex, ex); } } finally { Files.delete(zipFile); } }