Example usage for java.io File listFiles

List of usage examples for java.io File listFiles

Introduction

In this page you can find the example usage for java.io File listFiles.

Prototype

public File[] listFiles(FileFilter filter) 

Source Link

Document

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

Usage

From source file:TestDumpRecord.java

public static void main(String[] args) throws NITFException {
    List<String> argList = Arrays.asList(args);
    List<File> files = new LinkedList<File>();
    for (String arg : argList) {
        File f = new File(arg);
        if (f.isDirectory()) {
            File[] dirFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    String ext = FilenameUtils.getExtension(name).toLowerCase();
                    return ext.matches("nitf|nsf|ntf");
                }//from   w w  w  . j av a 2  s . co m
            });
            files.addAll(Arrays.asList(dirFiles));
        } else
            files.add(f);
    }

    Reader reader = new Reader();
    for (File file : files) {
        PrintStream out = System.out;

        out.println("=== " + file.getAbsolutePath() + " ===");
        IOHandle handle = new IOHandle(file.getAbsolutePath());
        Record record = reader.read(handle);
        dumpRecord(record, reader, out);
        handle.close();

        record.destruct(); // tells the memory manager to decrement the ref
        // count
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    File myDir = new File("C:/");
    // Define a filter for java source files beginning with F
    FilenameFilter select = new FileListFilter("F", "java");

    File[] contents = myDir.listFiles(select);

    if (contents != null) {
        System.out.println(//ww w . j  av  a 2 s  .  c om
                "\nThe " + contents.length + " matching items in the directory, " + myDir.getName() + ", are:");
        for (File file : contents) {
            System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file")
                    + " last modified on\n" + new Date(file.lastModified()));
        }
    } else {
        System.out.println(myDir.getName() + " is not a directory");
    }
    return;
}

From source file:de.fatalix.book.importer.CalibriImporter.java

public static void main(String[] args) throws IOException, URISyntaxException, SolrServerException {
    Gson gson = new Gson();
    CalibriImporterConfiguration config = gson.fromJson(args[0], CalibriImporterConfiguration.class);
    File importFolder = new File(config.getImportFolder());
    if (importFolder.isDirectory()) {
        File[] zipFiles = importFolder.listFiles(new FilenameFilter() {

            @Override//  www  .j a va  2s .  c o m
            public boolean accept(File dir, String name) {
                return name.endsWith(".zip");
            }
        });
        for (File zipFile : zipFiles) {
            try {
                processBooks(zipFile.toPath(), config.getSolrCore(), config.getSolrCore(),
                        config.getBatchSize());
                System.out.println("Processed file " + zipFile.getName());
            } catch (IOException ex) {
                ex.printStackTrace();

            }
        }
    } else {
        System.out.println("Import folder: " + importFolder.getAbsolutePath() + " cannot be read!");
    }
}

From source file:Main.java

public static void main(String[] args) {

    File f = new File("c:/test");

    FileFilter filter = new FileFilter() {
        @Override//  ww  w. ja  v  a2  s  . com
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    };

    // returns pathnames for files and directory
    File[] paths = f.listFiles(filter);

    for (File path : paths) {
        System.out.println(path);
    }
}

From source file:ai.emot.demo.EmotAIDemo.java

public static void main(String[] args) throws IOException, InterruptedException {
    if (args.length != 2) {
        printUsage();/*from   ww  w  . j ava 2  s .  c o  m*/
        System.exit(0);
    }

    String emotAIAPIBaseUrl = args[0];
    String accessToken = args[1];

    PathMatchingResourcePatternResolver fileResolver = new PathMatchingResourcePatternResolver(
            EmotAIDemo.class.getClassLoader());
    Resource[] resources = fileResolver.getResources("images");
    File dir = resources[0].getFile();
    File imagesDir = new File(dir, "/face/cropped");

    EmotAI emotAI = new EmotAITemplate(emotAIAPIBaseUrl, accessToken);

    // Create a display for the images
    ImageDisplay<Long> imageDisplay = new ImageDisplay<Long>(250, 250);

    for (File imageFile : imagesDir.listFiles(new JpegFileFilter())) {
        // Read each image
        BufferedImage image = ImageIO.read(imageFile);

        // Get the emotion profile for each image
        EmotionProfile emotionProfile = emotAI.emotionOperations().getFaceImageEmotionProfile(image);

        // Output emotion, and display image
        System.out.println(imageFile.getName() + " : " + emotionProfile);
        imageDisplay.onFrameUpdate(new SerializableBufferedImageAdapter(image), 1l);

        // Sleep for 1 second
        Thread.sleep(1000);

    }

    System.exit(1);
}

From source file:com.grantingersoll.intell.index.Indexer.java

public static void main(String[] args) throws Exception {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option wikipediaFileOpt = obuilder.withLongName("wikiFile").withRequired(true)
            .withArgument(abuilder.withName("wikiFile").withMinimum(1).withMaximum(1).create())
            .withDescription(//from w w w .j  a v a 2 s . c o m
                    "The path to the wikipedia dump file.  Maybe a directory containing wikipedia dump files."
                            + "  If a directory is specified, only .xml files are used.")
            .withShortName("w").create();

    Option numDocsOpt = obuilder.withLongName("numDocs").withRequired(false)
            .withArgument(abuilder.withName("numDocs").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to index").withShortName("n").create();

    Option solrURLOpt = obuilder.withLongName("solrURL").withRequired(false)
            .withArgument(abuilder.withName("solrURL").withMinimum(1).withMaximum(1).create())
            .withDescription("The URL where Solr lives").withShortName("s").create();

    Option solrBatchOpt = obuilder.withLongName("batch").withRequired(false)
            .withArgument(abuilder.withName("batch").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to include in each indexing batch").withShortName("b")
            .create();

    Group group = gbuilder.withName("Options").withOption(wikipediaFileOpt).withOption(numDocsOpt)
            .withOption(solrURLOpt).withOption(solrBatchOpt).create();

    Parser parser = new Parser();
    parser.setGroup(group);
    CommandLine cmdLine = parser.parse(args);

    File file;
    file = new File(cmdLine.getValue(wikipediaFileOpt).toString());
    File[] dumpFiles;
    if (file.isDirectory()) {
        dumpFiles = file.listFiles(new FilenameFilter() {
            public boolean accept(File file, String s) {
                return s.endsWith(".xml");
            }
        });
    } else {
        dumpFiles = new File[] { file };
    }

    int numDocs = Integer.MAX_VALUE;
    if (cmdLine.hasOption(numDocsOpt)) {
        numDocs = Integer.parseInt(cmdLine.getValue(numDocsOpt).toString());
    }
    String url = DEFAULT_SOLR_URL;
    if (cmdLine.hasOption(solrURLOpt)) {
        url = cmdLine.getValue(solrURLOpt).toString();
    }
    int batch = 100;
    if (cmdLine.hasOption(solrBatchOpt)) {
        batch = Integer.parseInt(cmdLine.getValue(solrBatchOpt).toString());
    }
    Indexer indexer = new Indexer(new CommonsHttpSolrServer(url));
    int total = 0;
    for (int i = 0; i < dumpFiles.length && total < numDocs; i++) {
        File dumpFile = dumpFiles[i];
        log.info("Indexing: " + file + " Num files to index: " + (numDocs - total));
        long start = System.currentTimeMillis();
        int totalFile = indexer.index(dumpFile, numDocs - total, batch);
        long finish = System.currentTimeMillis();
        if (log.isInfoEnabled()) {
            log.info("Indexing " + dumpFile + " took " + (finish - start) + " ms");
        }
        total += totalFile;
        log.info("Done Indexing: " + file + ". Indexed " + totalFile + " docs for that file and " + total
                + " overall.");

    }
    log.info("Indexed " + total + " docs overall.");
}

From source file:com.tamingtext.qa.WikipediaIndexer.java

public static void main(String[] args) throws Exception {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option wikipediaFileOpt = obuilder.withLongName("wikiFile").withRequired(true)
            .withArgument(abuilder.withName("wikiFile").withMinimum(1).withMaximum(1).create())
            .withDescription(/*from   w  w w  .j  av  a2s  . co m*/
                    "The path to the wikipedia dump file.  Maybe a directory containing wikipedia dump files."
                            + "  If a directory is specified, only .xml files are used.")
            .withShortName("w").create();

    Option numDocsOpt = obuilder.withLongName("numDocs").withRequired(false)
            .withArgument(abuilder.withName("numDocs").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to index").withShortName("n").create();

    Option solrURLOpt = obuilder.withLongName("solrURL").withRequired(false)
            .withArgument(abuilder.withName("solrURL").withMinimum(1).withMaximum(1).create())
            .withDescription("The URL where Solr lives").withShortName("s").create();

    Option solrBatchOpt = obuilder.withLongName("batch").withRequired(false)
            .withArgument(abuilder.withName("batch").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to include in each indexing batch").withShortName("b")
            .create();

    Group group = gbuilder.withName("Options").withOption(wikipediaFileOpt).withOption(numDocsOpt)
            .withOption(solrURLOpt).withOption(solrBatchOpt).create();

    Parser parser = new Parser();
    parser.setGroup(group);
    CommandLine cmdLine = parser.parse(args);

    File file;
    file = new File(cmdLine.getValue(wikipediaFileOpt).toString());
    File[] dumpFiles;
    if (file.isDirectory()) {
        dumpFiles = file.listFiles(new FilenameFilter() {
            public boolean accept(File file, String s) {
                return s.endsWith(".xml");
            }
        });
    } else {
        dumpFiles = new File[] { file };
    }

    int numDocs = Integer.MAX_VALUE;
    if (cmdLine.hasOption(numDocsOpt)) {
        numDocs = Integer.parseInt(cmdLine.getValue(numDocsOpt).toString());
    }
    String url = DEFAULT_SOLR_URL;
    if (cmdLine.hasOption(solrURLOpt)) {
        url = cmdLine.getValue(solrURLOpt).toString();
    }
    int batch = 100;
    if (cmdLine.hasOption(solrBatchOpt)) {
        batch = Integer.parseInt(cmdLine.getValue(solrBatchOpt).toString());
    }
    WikipediaIndexer indexer = new WikipediaIndexer(new CommonsHttpSolrServer(url));
    int total = 0;
    for (int i = 0; i < dumpFiles.length && total < numDocs; i++) {
        File dumpFile = dumpFiles[i];
        log.info("Indexing: " + file + " Num files to index: " + (numDocs - total));
        long start = System.currentTimeMillis();
        int totalFile = indexer.index(dumpFile, numDocs - total, batch);
        long finish = System.currentTimeMillis();
        if (log.isInfoEnabled()) {
            log.info("Indexing " + dumpFile + " took " + (finish - start) + " ms");
        }
        total += totalFile;
        log.info("Done Indexing: " + file + ". Indexed " + totalFile + " docs for that file and " + total
                + " overall.");

    }
    log.info("Indexed " + total + " docs overall.");
}

From source file:Main.java

public static void main(String[] args) {
    String dirPath = "C:\\";
    File dir = new File(dirPath);

    // Create a file filter to exclude any .SYS file
    FileFilter filter = file -> {
        if (file.isFile()) {
            String fileName = file.getName().toLowerCase();
            if (fileName.endsWith(".sys")) {
                return false;
            }/*from ww  w .  j  ava  2 s  .  co  m*/
        }
        return true;
    };

    File[] list = dir.listFiles(filter);

    for (File f : list) {
        if (f.isFile()) {
            System.out.println(f.getPath() + "  (File)");
        } else if (f.isDirectory()) {
            System.out.println(f.getPath() + "  (Directory)");
        }
    }
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

/**
 * @param args/*  ww w  . j ava 2s .c  o  m*/
 */
public static void main(String[] args) {
    System.out.println("Translate.main() 1");
    Console console = System.console();

    System.out.println("give path to folder that contains properties files");
    Scanner scanIn = new Scanner(System.in);

    try {
        // TODO Auto-generated method stub
        String sWhatever;

        System.out.println("Translate.main() 2");
        sWhatever = scanIn.nextLine();
        System.out.println("Translate.main() 3");

        System.out.println(sWhatever);

        File inDir = new File(sWhatever);

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith("properties");
            }
        };
        File[] listFiles = inDir.listFiles(filter);
        for (File file : listFiles) {

            prapareFileToTranslate(file, inDir);

        }

        System.out.println("please translate text files and press enter");
        String readLine = scanIn.nextLine();
        System.out.println("Translate.main() 4");
        for (File file : listFiles) {

            File values = new File(file.getParentFile(), file.getName() + ".txt");
            writeBackValues(values, file);
            values.delete();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        scanIn.close();
    }

}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from   ww  w  .  j av a  2 s . c  om*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}