Example usage for java.nio.file Files newDirectoryStream

List of usage examples for java.nio.file Files newDirectoryStream

Introduction

In this page you can find the example usage for java.nio.file Files newDirectoryStream.

Prototype

public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException 

Source Link

Document

Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.

Usage

From source file:Main.java

public static void main(String[] args) {
    Path directory = Paths.get("c:/");
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path file : directoryStream) {
            System.out.println(file.getFileName());
        }//from   w  w  w. ja  va2s.c  o  m
    } catch (IOException | DirectoryIteratorException ex) {
        ex.printStackTrace();
    }
}

From source file:Test.java

public static void main(String[] args) {
    Path directory = Paths.get("/home");
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path file : directoryStream) {
            System.out.println(file.getFileName());
        }/*from w ww  .j a v a 2 s .c o  m*/
    } catch (IOException | DirectoryIteratorException ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {

    Path path = Paths.get("C:/tutorial/Java/JavaFX");

    //no filter applyied
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
        for (Path file : ds) {
            System.out.println(file.getFileName());
        }/*from w w  w . j a  v  a2  s. c  o m*/
    } catch (IOException e) {
        System.err.println(e);
    }

}

From source file:Test.java

public static void main(String args[]) throws IOException {
    Path path = Paths.get("home/docs");
    SecureDirectoryStream<Path> sds = (SecureDirectoryStream) Files.newDirectoryStream(path);
    PosixFileAttributeView view = sds.getFileAttributeView(PosixFileAttributeView.class);
    PosixFileAttributes attributes = view.readAttributes();
    Set<PosixFilePermission> permissions = attributes.permissions();

    for (PosixFilePermission permission : permissions) {
        System.out.print(permission.toString() + ' ');
    }//from www .ja v a2 s  .  c  o  m
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Map<String, String> attributes = new HashMap<>();
    attributes.put("create", "true");
    URI zipFile = URI.create("jar:file:/home.zip");
    try (FileSystem zipFileSys = FileSystems.newFileSystem(zipFile, attributes);) {
        Path path = zipFileSys.getPath("docs");
        Files.createDirectory(path);
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(zipFileSys.getPath("/"));) {
            for (Path file : directoryStream) {
                System.out.println(file.getFileName());
            }//from   ww  w.j  av a2 s .co m
        }
    }
}

From source file:training.w2d34e2.java

public static void main(String[] args) {

    final String srcDirPath = "/Users/venkataraghav/Work/training/Sample/Week2/source";
    final String desDirPath = "/Users/venkataraghav/Work/training/Sample/Week2/destination";

    DirectoryStream<Path> directoryStream = null;

    try {/*w w w .  j ava 2 s  .  c o m*/

        directoryStream = Files.newDirectoryStream(Paths.get(srcDirPath));

        File f = null;

        for (Path filePath : directoryStream) {

            String fName = filePath.getFileName().toString();

            f = new File(desDirPath + "/" + fName);

            int i = 0;

            while (f.exists()) {

                i++;

                String name = fName.substring(0, fName.indexOf('.'));

                String extension = fName.substring(fName.indexOf('.'));

                f = new File(desDirPath + "/" + name + "-" + i + extension);

            }

            FileUtils.copyFile(filePath.toFile(), f);
        }

        directoryStream.close();

    }

    catch (IOException ioe) {

        ioe.printStackTrace();
    }

}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args/* w  w w.  ja  v  a 2s  .  com*/
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

public static void main(String[] args) throws IOException {
    if (logger == null) {
        System.out.println("About to initialize Log4j");
        logger = LogManager.getLogger();
        System.out.println("Finished initializing Log4j");
    }/* ww w  .j  a  v a  2s . c  o  m*/

    logger.debug("Entering main()");

    // WIP: the following command line code was pulled from FITS
    Options options = new Options();
    Option inputFileOption = new Option(PARAM_I, true, "input file");
    options.addOption(inputFileOption);
    options.addOption(PARAM_V, false, "print version information");
    options.addOption(PARAM_H, false, "help information");
    options.addOption(PARAM_O, true, "output sub-directory");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // print version info
    if (cmd.hasOption(PARAM_V)) {
        if (StringUtils.isEmpty(applicationVersion)) {
            applicationVersion = "<not set>";
            System.exit(1);
        }
        System.out.println("Version: " + applicationVersion);
        System.exit(0);
    }

    // print help info
    if (cmd.hasOption(PARAM_H)) {
        displayHelp();
        System.exit(0);
    }

    // input parameter
    if (cmd.hasOption(PARAM_I)) {
        String input = cmd.getOptionValue(PARAM_I);
        boolean hasValue = cmd.hasOption(PARAM_I);
        logger.debug("Has option {} value: [{}]", PARAM_I, hasValue);
        String paramVal = cmd.getOptionValue(PARAM_I);
        logger.debug("value of option: [{}] ****", paramVal);

        File inputFile = new File(input);
        if (!inputFile.exists()) {
            logger.warn("{} does not exist or is not readable.", input);
            System.exit(1);
        }

        String subDir = cmd.getOptionValue(PARAM_O);
        PdfaConvert convert;
        if (!StringUtils.isEmpty(subDir)) {
            convert = new PdfaConvert(subDir);
        } else {
            convert = new PdfaConvert();
        }
        if (inputFile.isDirectory()) {
            if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) {
                logger.warn("Input directory is empty, nothing to process.");
                System.exit(1);
            } else {
                logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(),
                        inputFile.listFiles().length);
                DirectoryStream<Path> dirStream = null;
                dirStream = Files.newDirectoryStream(inputFile.toPath());
                for (Path filePath : dirStream) {
                    logger.debug("Have file name: {}", filePath.toString());
                    // Note: only handling files, not recursively going into sub-directories
                    if (filePath.toFile().isFile()) {
                        // Catch possible exception for each file so can handle other files in directory.
                        try {
                            convert.examine(filePath.toFile());
                        } catch (Exception e) {
                            logger.error("Problem processing file: {} -- Error message: {}",
                                    filePath.getFileName(), e.getMessage());
                        }
                    } else {
                        logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing
                    }
                }
                dirStream.close();
            }
        } else {
            logger.debug("About to process file: {}", inputFile.getPath());
            try {
                convert.examine(inputFile);
            } catch (Exception e) {
                logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage());
                logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(),
                        e.getMessage(), e);
            }
        }
    } else {
        System.err.println("Missing required option: " + PARAM_I);
        displayHelp();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:com.nwn.NwnFileHandler.java

/**
 * Get files in given directory/*from w ww .j  av a 2  s .co m*/
 * @param dir Path to directory for parsing
 * @return ArrayList of files in directory
 */
public static ArrayList<Path> getFilesInDirectory(Path dir) {
    ArrayList<Path> filesInDir = new ArrayList<Path>();
    try {
        DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);
        for (Path file : dirStream) {
            filesInDir.add(file);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return filesInDir;
}

From source file:com.basistech.rosette.apimodel.NonNullTest.java

@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() throws URISyntaxException, IOException {
    File dir = new File("src/test/data");
    Collection<Object[]> params = new ArrayList<>();
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(dir.toPath())) {
        for (Path file : paths) {
            if (file.toString().endsWith(".json")) {
                String className = file.getFileName().toString().replace(".json", "");
                params.add(new Object[] { NonNullTest.class.getPackage().getName() + "." + className,
                        file.toFile() });
            }/* w  ww.j av  a 2 s. co  m*/
        }
    }
    return params;
}