/** * Recurse down a directory tree, checking all child directories. * @param dir * @throws DiskErrorException */ public static void checkDirs(File dir) throws DiskErrorException { checkDir(dir); IOException ex = null; try (DirectoryStream<java.nio.file.Path> stream = Files.newDirectoryStream(dir.toPath())) { for (java.nio.file.Path entry: stream) { File child = entry.toFile(); if (child.isDirectory()) { checkDirs(child); } } } catch (DirectoryIteratorException de) { ex = de.getCause(); } catch (IOException ie) { ex = ie; } if (ex != null) { throw new DiskErrorException("I/O error when open a directory: " + dir.toString(), ex); } }
/** * Return the complete list of files in a directory as strings.<p/> * * This is better than File#listDir because it does not ignore IOExceptions. * * @param dir The directory to list. * @param filter If non-null, the filter to use when listing * this directory. * @return The list of files in the directory. * * @throws IOException On I/O error */ public static List<String> listDirectory(File dir, FilenameFilter filter) throws IOException { ArrayList<String> list = new ArrayList<String> (); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir.toPath())) { for (Path entry: stream) { String fileName = entry.getFileName().toString(); if ((filter == null) || filter.accept(dir, fileName)) { list.add(fileName); } } } catch (DirectoryIteratorException e) { throw e.getCause(); } return list; }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: Path dir = Paths.get(txt_path.getText()); if (dir.getParent()==null) { return; } dtm.setRowCount(0); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir.getParent())) { for (Path file : stream) { dtm.addRow(new Object[]{file.getFileName()}); } } catch (IOException | DirectoryIteratorException x) { } txt_path.setText(dir.getParent().toString()); }
@Test public void testEmptyPackageDirectory(Path base) throws Exception { Path src = base.resolve("src"); createSources(src); // need an empty package directory, to check whether // the behavior of subpackage and package Path pkgdir = src.resolve("m1/m1pro/"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(pkgdir, "*.java")) { for (Path entry : stream) { Files.deleteIfExists(entry); } } catch (DirectoryIteratorException ex) { // I/O error encounted during the iteration throw ex.getCause(); } execTask("--module-source-path", src.toString(), "-subpackages", "m1/m1pro"); checkPackagesSpecified("m1pro", "m1pro.pro1", "m1pro.pro2"); // empty package directory should cause an error execNegativeTask("--module-source-path", src.toString(), "m1/m1pro"); }
PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey) throws IOException { super(dir, watcher); this.fileKey = fileKey; this.valid = true; this.tickCount = 0; this.entries = new HashMap<Path,CacheEntry>(); // get the initial entries in the directory try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry: stream) { // don't follow links long lastModified = Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis(); entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount)); } } catch (DirectoryIteratorException e) { throw e.getCause(); } }
/** * Read a.yaml file according to a class type. * * @param path folder which contain the config files * @param classType Class type of the.yaml bean * @param fileNameRegex file name regex * @param <T> Class T * @return Config file bean * @throws CarbonIdentityMgtConfigException Error in reading configuration file */ public static <T> List<T> readConfigFiles(Path path, Class<T> classType, String fileNameRegex) throws CarbonIdentityMgtConfigException { List<T> configEntries = new ArrayList<>(); if (Files.exists(path)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, fileNameRegex)) { for (Path file : stream) { Reader in = new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8); CustomClassLoaderConstructor constructor = new CustomClassLoaderConstructor(classType.getClassLoader()); Yaml yaml = new Yaml(constructor); yaml.setBeanAccess(BeanAccess.FIELD); configEntries.add(yaml.loadAs(in, classType)); } } catch (DirectoryIteratorException | IOException e) { throw new CarbonIdentityMgtConfigException(String.format("Failed to read identity connector files " + "from path: %s", path.toString()), e); } } return configEntries; }
public static File getRandomCasa(int size) { List<String> casas = new ArrayList<>(); Path dir = Paths.get(Main.getPlugin().getDataFolder() + File.separator + "casas" + File.separator); if (Files.exists(dir)) { try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path path : stream) { String fn = path.getFileName().toString().split(".schematic")[0]; if (fn.split("-").length == 2) { int smin = Integer.parseInt(fn.split("_")[1].split("-")[0]); int smax = Integer.parseInt(fn.split("_")[1].split("-")[1]); if (size >= smin && size <= smax) { casas.add(path.getFileName().toString()); } } } } catch (IOException | DirectoryIteratorException e) { e.printStackTrace(); } if (!casas.isEmpty()) { int i = new Random().nextInt(casas.size()); return new File(dir.toString(), casas.get(i)); } } return null; }
/** * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the * test directory. * * @throws IOException Thrown if the test directory could not be deleted */ @After public void tearDown() throws IOException { //Unset Mojo instance mojo = null; //Delete test directory final Path testDir = Paths.get(TEST_DIR); if (Files.exists(testDir)) { //First get all files in the test directory (if the test directory //exists and delete them. This is necessary because there is no //method for recursivly deleting a directory in the Java API. try (final DirectoryStream<Path> files = Files.newDirectoryStream( testDir)) { for (final Path file : files) { Files.deleteIfExists(file); } } catch (DirectoryIteratorException ex) { throw ex.getCause(); } //Delete the (now empty) test directory. Files.deleteIfExists(testDir); } }
private static Map<String, Collection<Path>> collectPlotFiles(List<String> plotDirectories, String numericAccountId) { Map<String, Collection<Path>> plotFilesLookup = new HashMap<>(); for(String plotDirectory : plotDirectories) { Path folderPath = Paths.get(plotDirectory); try (DirectoryStream<Path> plotFilesStream = Files.newDirectoryStream(folderPath)) { List<Path> plotFilePaths = new ArrayList<>(); for(Path plotFilePath : plotFilesStream) { if(plotFilePath.toString().contains(numericAccountId)) { plotFilePaths.add(plotFilePath); } } plotFilesLookup.put(plotDirectory, plotFilePaths); } catch(IOException | DirectoryIteratorException e) { LOG.error(e.getMessage()); } } return plotFilesLookup; }
private static List<Path> listFiles(Path dir) { if ((dir != null) && Files.isDirectory(dir)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { ImmutableList.Builder<Path> builder = ImmutableList.builder(); for (Path file : stream) { builder.add(file); } return builder.build(); } catch (IOException | DirectoryIteratorException x) { log.warn(x, "Warning."); throw Throwables.propagate(x); } } return ImmutableList.of(); }
private boolean fillContentList(Path dir) { contentlist.clear(); // add parent path only if possible Path parentPath = dir.getParent(); if (parentPath != null) { contentlist.add(new PathFixture(parentPath)); } if (dir != null && Files.isDirectory(dir)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry : stream) { contentlist.add(new PathFixture(entry)); } } catch (DirectoryIteratorException | IOException ex) { log.warn(ex.getMessage()); } } return (contentlist.size() >= 1 ? true : false); }
@Override protected synchronized Path computeNext() { checkOpen(); try { if (fileNames == null) { fileNames = view.snapshotWorkingDirectoryEntries().iterator(); } while (fileNames.hasNext()) { Name name = fileNames.next(); Path path = view.getWorkingDirectoryPath().resolve(name); if (filter.accept(path)) { return path; } } return endOfData(); } catch (IOException e) { throw new DirectoryIteratorException(e); } }
/** * @param dirStructure the directory structure the destination should adhere to * @param sourcePath the path to the files to move * @param destinationPath the path to where the files should be moved */ public FileMover(DirectoryStructure dirStructure, String sourcePath, String destinationPath) { this.dirStructure = dirStructure; this.sourcePath = sourcePath; this.destinationPath = destinationPath; this.verbose = false; Path sourceDir = Paths.get(this.sourcePath + "/"); //Construct the list of all the files to move DirectoryStream<Path> stream; try { stream = Files.newDirectoryStream(sourceDir); for(Path currentFile : stream) { BasicFileAttributes fileAttributes = Files.readAttributes(currentFile, BasicFileAttributes.class); System.out.println(currentFile.toString()); if(!fileAttributes.isDirectory() || Arrays.asList(getAppleFiles()).contains(getFileExtension(currentFile))) { this.filesToMove.add(currentFile); } } } catch(IOException | DirectoryIteratorException e) { System.err.println(e); } }
private long countSubDirs(Path path) throws IOException { try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, Files::isDirectory)) { return Iterables.size(ds); } catch (DirectoryIteratorException e) { throw new IOException(e); } }
public int readdir(Path path, Pointer buf, FuseFillDir filler, long offset, FuseFileInfo fi) throws IOException { // fill in names and basic file attributes - however only the filetype is used... // Files.walkFileTree(node, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // FileStat stat = attrUtil.basicFileAttributesToFileStat(attrs); // if (attrs.isDirectory()) { // stat.st_mode.set(FileStat.S_IFDIR | FileStat.ALL_READ | FileStat.S_IXUGO); // } else { // stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); // } // filter.apply(buf, file.getFileName().toString(), stat, 0); // return FileVisitResult.CONTINUE; // } // }); // just fill in names, getattr gets called for each entry anyway try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { Iterator<Path> sameAndParent = Iterators.forArray(SAME_DIR, PARENT_DIR); Iterator<Path> iter = Iterators.concat(sameAndParent, ds.iterator()); while (iter.hasNext()) { String fileName = iter.next().getFileName().toString(); if (filler.apply(buf, fileName, null, 0) != 0) { return -ErrorCodes.ENOMEM(); } } return 0; } catch (DirectoryIteratorException e) { throw new IOException(e); } }
@Override public Iterable<Path> children(Path dir) { if (Files.isDirectory(dir, NOFOLLOW_LINKS)) { try { return listFiles(dir); } catch (IOException e) { // the exception thrown when iterating a DirectoryStream if an I/O exception occurs throw new DirectoryIteratorException(e); } } return ImmutableList.of(); }
/** * Secure method for deleting the contents of a directory using {@code SecureDirectoryStream}. * Returns a collection of exceptions that occurred or null if no exceptions were thrown. */ @Nullable private static Collection<IOException> deleteDirectoryContentsSecure( SecureDirectoryStream<Path> dir) { Collection<IOException> exceptions = null; try { for (Path path : dir) { exceptions = concat(exceptions, deleteRecursivelySecure(dir, path.getFileName())); } return exceptions; } catch (DirectoryIteratorException e) { return addException(exceptions, e.getCause()); } }
/** * Simple, insecure method for deleting the contents of a directory for file systems that don't * support {@code SecureDirectoryStream}. Returns a collection of exceptions that occurred or * null if no exceptions were thrown. */ @Nullable private static Collection<IOException> deleteDirectoryContentsInsecure( DirectoryStream<Path> dir) { Collection<IOException> exceptions = null; try { for (Path entry : dir) { exceptions = concat(exceptions, deleteRecursivelyInsecure(entry)); } return exceptions; } catch (DirectoryIteratorException e) { return addException(exceptions, e.getCause()); } }
private void listele() { dtm.setRowCount(0); Path dir = Paths.get(txt_path.getText()); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file : stream) { dtm.addRow(new Object[]{file.getFileName()}); } } catch (IOException | DirectoryIteratorException x) { } }
public final static List<Path> listSourceFiles(Path dir, String wildcard) { List<Path> result = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, wildcard)) { for (Path entry : stream) { result.add(entry); } } catch (DirectoryIteratorException | IOException ex) { // I/O error encounted during the iteration, the cause is an // IOException ex.printStackTrace(); } return result; }
private MCRPath getPath(MCRFilesystemNode[] children, int index) { try { MCRPath path = MCRPath.toMCRPath(mcrDirectoryStream.path.resolve(children[index].getName())); LOGGER.debug(() -> "getting path at index " + index + ": " + path); return path; } catch (RuntimeException e) { throw new DirectoryIteratorException(new IOException(e)); } }
private void deletarHistoricos() { Path p = Paths.get(getDataFolder() + File.separator + "checkbans"); if (Files.exists(p)) { try(DirectoryStream<Path> stream = Files.newDirectoryStream(p)) { for (Path path : stream) { Files.delete(path); } Files.delete(p); } catch (IOException | DirectoryIteratorException e) { e.printStackTrace(); } } }
private static List<Path> listResFiles(Path dir, String pattern) throws IOException { List<Path> result = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, pattern)) { for (Path entry : stream) { result.add(entry); } } catch (DirectoryIteratorException ex) { throw ex.getCause(); } return result; }
/** * Parse the files harvested from PoolParty and extract the * metadata. * @param pPprojectId The PoolParty project id. * @return The results of the metadata extraction. */ public final HashMap<String, Object> extractMetadata( final String pPprojectId) { Path dir = Paths.get(ToolkitFileUtils.getMetadataOutputPath( pPprojectId)); HashMap<String, Object> results = new HashMap<String, Object>(); ConceptHandler conceptHandler = new ConceptHandler(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry: stream) { conceptHandler.setSource(entry.getFileName().toString()); RDFFormat format = Rio.getParserFormatForFileName( entry.toString()); RDFParser rdfParser = Rio.createParser(format); rdfParser.setRDFHandler(conceptHandler); FileInputStream is = new FileInputStream(entry.toString()); logger.debug("Reading RDF:" + entry.toString()); rdfParser.parse(is, entry.toString()); } } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException ex) { results.put(TaskStatus.EXCEPTION, "Exception in extractMetadata while Parsing RDF"); logger.error("Exception in extractMetadata while Parsing RDF:", ex); return results; } results.putAll(conceptHandler.getMetadata()); results.put("concept_count", Integer.toString( conceptHandler.getCountedConcepts())); return results; }
@Override public void backupToArchive(RawDataBackup backup) throws IOException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) { for (Path file : stream) { String path = file.getFileName().toString(); try (final OutputStream os = backup.newEntry(path)) { Files.copy(getDataDir().resolve(path), os); } finally { backup.closeEntry(); } } } catch (IOException | DirectoryIteratorException die) { LOG.error("Could not read directory: " + directory.toAbsolutePath().toString()); } }
public DirectoryStream<Path> newDirectoryStream( Path dir, DirectoryStream.Filter<? super Path> filter ) throws IOException { final ArrayList<Path> list = map.get( dir ); if( list == null ) { final ArrayList<Path> paths = map.computeIfAbsent( dir, ( d ) -> new ArrayList<>() ); return java.nio.file.Files.newDirectoryStream( dir, ( file ) -> { paths.add( file ); exists.put( file, true ); return filter.accept( file ); } ); } return new DirectoryStream<Path>() { @Override public Iterator<Path> iterator() { return Iterators.filter( list.iterator(), ( p ) -> { try { return filter.accept( p ); } catch( IOException e ) { throw new DirectoryIteratorException( e ); } } ); } @Override public void close() throws IOException { } }; }
/** * Update the application file with the content from the update directory. * @param applicationFile The application file to be updated * @param updateDir The update directory holding the new file versions * @param removeUpdateFiles If true, the updated files are deleted from the update directory * @return The path to the newly updated application file, or null if there was no update performed * @throws IOException In case of an error */ public static Path update(Path applicationFile, Path updateDir, boolean removeUpdateFiles) throws IOException { Path newApplicationJar = null; // Extract the application name from the application file String applicationName = applicationFile.getFileName().toString(); // Strip the extension applicationName = applicationName.substring(0, applicationName.lastIndexOf(".")); ArrayList<Path> updateFiles = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(updateDir, applicationName + "*.{jar,JAR,war,WAR,rar,RAR,ear,EAR}")) { for (Path entry : stream) { updateFiles.add(entry); } } catch (DirectoryIteratorException ex) { // I/O error encounted during the iteration, the cause is an IOException throw ex.getCause(); } if (!updateFiles.isEmpty()) { Path updateFile = updateFiles.get(0); newApplicationJar = Files.copy(updateFile, applicationFile, StandardCopyOption.REPLACE_EXISTING); if (removeUpdateFiles) { Files.delete(updateFile); } } return newApplicationJar; }
List<Path> listPhenotypeDataDirectories(Path dir) { List<Path> result = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry : stream) { if (entry.toString().endsWith("_phenotype")) { logger.info("Found phenotype data directory {}", entry); result.add(entry); } } } catch (DirectoryIteratorException | IOException ex) { // I/O error encounted during the iteration, the cause is an IOException throw new UndefinedDataDirectoryException("Unable to read/find valid phenotype data directory"); } return result; }