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() 

Source Link

Document

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Usage

From source file:org.eclipse.swt.snippets.Snippet8.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Lazy Tree");
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
        TreeItem root = new TreeItem(tree, 0);
        root.setText(roots[i].toString());
        root.setData(roots[i]);/*w ww .  j a v  a 2 s  .c om*/
        new TreeItem(root, 0);
    }
    tree.addListener(SWT.Expand, event -> {
        final TreeItem root = (TreeItem) event.item;
        TreeItem[] items = root.getItems();
        for (int i1 = 0; i1 < items.length; i1++) {
            if (items[i1].getData() != null)
                return;
            items[i1].dispose();
        }
        File file = (File) root.getData();
        File[] files = file.listFiles();
        if (files == null)
            return;
        for (int i2 = 0; i2 < files.length; i2++) {
            TreeItem item = new TreeItem(root, 0);
            item.setText(files[i2].getName());
            item.setData(files[i2]);
            if (files[i2].isDirectory()) {
                new TreeItem(item, 0);
            }
        }
    });
    Point size = tree.computeSize(300, SWT.DEFAULT);
    int width = Math.max(300, size.x);
    int height = Math.max(300, size.y);
    shell.setSize(shell.computeSize(width, height));
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:cpm.openAtlas.bundleInfo.maker.BundleMakeBooter.java

public static void main(String[] args) throws JSONException, IOException {
    if (args.length != 2) {
        throw new IOException(" args to less , usage plugin_dir out_put_json_path");

    }/*from  w w w .  j  a  v  a2  s  . com*/

    String path = args[0];
    String targetFile = args[1];
    File dirFile = new File(path);
    JSONArray jsonArray = new JSONArray();
    File[] files = dirFile.listFiles();
    for (File file : files) {
        if (file.getAbsolutePath().contains("libcom")) {
            PackageLite packageLit = PackageLite.parse(file.getAbsolutePath());
            jsonArray.put(packageLit.getBundleInfo());
            //            try {
            //                packageLit.getBundleInfo().toString();
            //            } catch (JSONException e) {
            //               // TODO Auto-generated catch block
            //               e.printStackTrace();
            //            }
        }

    }
    org.apache.commons.io.FileUtils.writeStringToFile(new File(targetFile), jsonArray.toString());
    System.out.println(jsonArray.toString());
}

From source file:com.openAtlas.bundleInfo.maker.BundleMakeBooter.java

public static void main(String[] args) throws JSONException, IOException {
    //if(args.length!=2){
    //   throw new  IOException(" args to less , usage plugin_dir out_put_json_path");
    //}/*from   w ww  . j  a v a2s. co m*/

    args = new String[2];
    args[0] = "C:\\Users\\kltz\\Desktop\\AtlasDemo\\plugin";
    args[1] = "C:\\Users\\kltz\\Desktop\\AtlasDemo\\plugin\\bundle-info.json";

    String path = args[0];
    ApkPreProcess.preProcess(path);
    String targetFile = args[1];
    File dirFile = new File(path);
    JSONArray jsonArray = new JSONArray();
    File[] files = dirFile.listFiles();
    for (File file : files) {
        if (file.getAbsolutePath().contains("libcom")) {
            PackageLite packageLit = PackageLite.parse(file.getAbsolutePath());
            jsonArray.put(packageLit.getBundleInfo());
            //            try {
            //                packageLit.getBundleInfo().toString();
            //            } catch (JSONException e) {
            //               // TODO Auto-generated catch block
            //               e.printStackTrace();
            //            }
        }

    }
    org.apache.commons.io.FileUtils.writeStringToFile(new File(targetFile), jsonArray.toString());
    System.out.println(jsonArray.toString());
}

From source file:de.mirkosertic.invertedindex.core.FullIndexRun.java

public static void main(String[] args) throws IOException {
    InvertedIndex theIndex = new InvertedIndex();
    UpdateIndexHandler theIndexHandler = new UpdateIndexHandler(theIndex);
    Tokenizer theTokenizer = new Tokenizer(new ToLowercaseTokenHandler(theIndexHandler));

    File theOrigin = new File("/home/sertic/ownCloud/Textcontent");
    for (File theFile : theOrigin.listFiles()) {
        System.out.println("Indexing " + theFile);
        String theFileContent = IOUtils.toString(new FileReader(theFile));
        theTokenizer.process(new Document(theFile.getName(), theFileContent));
    }/*from   w  w  w .  j av  a  2s  .  c o m*/

    System.out.println(theIndex.getTokenCount() + " unique postings");
    System.out.println(theIndex.getDocumentCount() + " documents");

    theIndex.postings.entrySet().stream()
            .sorted((o1, o2) -> ((Integer) o1.getValue().getOccoursInDocuments().size())
                    .compareTo(o2.getValue().getOccoursInDocuments().size()))
            .forEach(t -> {
                System.out.println(t.getKey() + " -> " + t.getValue().getOccoursInDocuments().size());
            });

    System.out.println("Query");

    Result theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    System.out.println(theResult.getSize());
    for (int i = 0; i < theResult.getSize(); i++) {
        System.out.println(theResult.getDoc(i).getName());

        System.out.println(theIndex.rebuildContentFor(theResult.getDoc(i)));
    }

    long theCount = 100000;
    long theStart = System.currentTimeMillis();
    for (int i = 0; i < theCount; i++) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
    double theDuration = System.currentTimeMillis() - theStart;

    System.out.println(theCount + " Queries took " + theDuration + "ms");
    System.out.println(theDuration / theCount);

    while (true) {
        theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" }));
    }
}

From source file:uk.ac.kcl.Main.java

public static void main(String[] args) {
    File folder = new File(args[0]);
    File[] listOfFiles = folder.listFiles();
    assert listOfFiles != null;
    for (File listOfFile : listOfFiles) {
        if (listOfFile.isFile()) {
            if (listOfFile.getName().endsWith(".properties")) {
                System.out.println("Properties sile found:" + listOfFile.getName()
                        + ". Attempting to launch application context");
                Properties properties = new Properties();
                InputStream input;
                try {
                    input = new FileInputStream(listOfFile);
                    properties.load(input);
                    if (properties.getProperty("globalSocketTimeout") != null) {
                        TcpHelper.setSocketTimeout(
                                Integer.valueOf(properties.getProperty("globalSocketTimeout")));
                    }/*from   ww w  .  j a  v a 2s  . c o  m*/
                    Map<String, Object> map = new HashMap<>();
                    properties.forEach((k, v) -> {
                        map.put(k.toString(), v);
                    });
                    ConfigurableEnvironment environment = new StandardEnvironment();
                    MutablePropertySources propertySources = environment.getPropertySources();
                    propertySources.addFirst(new MapPropertySource(listOfFile.getName(), map));
                    @SuppressWarnings("resource")
                    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                    ctx.registerShutdownHook();
                    ctx.setEnvironment(environment);
                    String scheduling;
                    try {
                        scheduling = properties.getProperty("scheduler.useScheduling");
                        if (scheduling.equalsIgnoreCase("true")) {
                            ctx.register(ScheduledJobLauncher.class);
                            ctx.refresh();
                        } else if (scheduling.equalsIgnoreCase("false")) {
                            ctx.register(SingleJobLauncher.class);
                            ctx.refresh();
                            SingleJobLauncher launcher = ctx.getBean(SingleJobLauncher.class);
                            launcher.launchJob();
                        } else if (scheduling.equalsIgnoreCase("slave")) {
                            ctx.register(JobConfiguration.class);
                            ctx.refresh();
                        } else {
                            throw new RuntimeException(
                                    "useScheduling not configured. Must be true, false or slave");
                        }
                    } catch (NullPointerException ex) {
                        throw new RuntimeException(
                                "useScheduling not configured. Must be true, false or slave");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:edu.usc.ee599.CommunityStats.java

public static void main(String[] args) throws Exception {

    File dir = new File("results5");
    PrintWriter writer = new PrintWriter(new FileWriter("results5_stats.txt"));

    File[] files = dir.listFiles();

    DescriptiveStatistics statistics1 = new DescriptiveStatistics();
    DescriptiveStatistics statistics2 = new DescriptiveStatistics();
    for (File file : files) {

        BufferedReader reader = new BufferedReader(new FileReader(file));

        String line1 = reader.readLine();
        String line2 = reader.readLine();

        int balanced = Integer.parseInt(line1.split(",")[1]);
        int unbalanced = Integer.parseInt(line2.split(",")[1]);

        double bp = (double) balanced / (double) (balanced + unbalanced);
        double up = (double) unbalanced / (double) (balanced + unbalanced);

        statistics1.addValue(bp);//w w  w  .ja  v a2  s.co  m
        statistics2.addValue(up);

    }

    writer.println("AVG Balanced %: " + statistics1.getMean());
    writer.println("AVG Unbalanced %: " + statistics2.getMean());

    writer.println("STD Balanced %: " + statistics1.getStandardDeviation());
    writer.println("STD Unbalanced %: " + statistics2.getStandardDeviation());

    writer.flush();
    writer.close();

}

From source file:ie.pars.bnc.preprocess.MainBNCProcess.java

/**
 * Main method use for processing BNC text. Claws PoSs are replaced by
 * Stanford CoreNLP results for consistency with the rest of data! Currently
 * the structure of BNC is mainly discarded, only paragraphs and sentences
 *
 * @param sugare/*from w w  w  .  j a  v a2  s.c o  m*/
 * @throws IOException
 * @throws ArchiveException
 * @throws Exception
 */
public static void main(String[] sugare) throws IOException, ArchiveException, Exception {
    pathInput = sugare[0];
    pathOutput = sugare[1];
    letter = sugare[2];
    filesProcesed = new TreeSet();

    File folder = new File(pathOutput);
    if (folder.exists()) {
        for (File f : folder.listFiles()) {
            if (f.isFile()) {
                String pfile = f.getName().split("\\.")[0];
                filesProcesed.add(pfile);
            }
        }
    } else {
        folder.mkdirs();
    }
    getZippedFile();
}

From source file:com.taobao.tddl.common.SQLPreParserTest.java

public static void main(String[] args) throws IOException {
    //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-icsg-db0-db15-group-20100901100337-export.xlsx";
    //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-tcsg-instance-group-20100901100641-export.xlsx";

    int count = 0;
    long time = 0;

    File home = new File(System.getProperty("user.dir") + "/appsqls");
    for (File f : home.listFiles()) {
        if (f.isDirectory() || !f.getName().endsWith(".xlsx")) {
            continue;
        }/*from   w  ww  .j  av a  2 s.  c  o m*/
        log.info("---------------------- " + f.getAbsolutePath());
        faillog.info("---------------------- " + f.getAbsolutePath());
        Workbook wb = new XSSFWorkbook(new FileInputStream(f));
        Sheet sheet = wb.getSheetAt(0);
        for (Row row : sheet) {
            Cell cell = row.getCell(2);
            if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) {
                String sql = cell.getStringCellValue();

                long t0 = System.currentTimeMillis();
                String tableName = SQLPreParser.findTableName(sql);
                time += System.currentTimeMillis() - t0;
                count++;

                log.info(tableName + " <-- " + sql);
                if (tableName == null) {
                    sql = sql.trim().toLowerCase();
                    if (isCRUD(sql)) {
                        System.out.println("failed:" + sql);
                        faillog.error("failed:" + sql);
                    }
                }
            }
        }
        wb = null;
    }
    faillog.fatal("------------------------------- finished --------------------------");
    faillog.fatal(count + " sql parsed, total time:" + time + ". average time use per sql:"
            + (double) time / count + "ms/sql");
}

From source file:com.apipulse.bastion.Main.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    log.info("Bastion starting. Loading chains");
    final File dir = new File("etc/chains");

    final LinkedList<ActorRef> chains = new LinkedList<ActorRef>();
    for (File file : dir.listFiles()) {
        if (!file.getName().startsWith(".") && file.getName().endsWith(".yaml")) {
            log.info("Loading chain: " + file.getName());
            ChainConfig config = new ChainConfig(IOUtils.toString(new FileReader(file)));
            ActorRef ref = BastionActors.getInstance().initChain(config.getName(),
                    Class.forName(config.getQualifiedClass()));
            Iterator<StageConfig> iterator = config.getStages().iterator();
            while (iterator.hasNext())
                ref.tell(iterator.next(), null);
            chains.add(ref);/*from  w  w  w. java 2 s  .c o  m*/
        }
    }
    SpringApplication app = new SpringApplication();
    HashSet<Object> objects = new HashSet<Object>();
    objects.add(ApiController.class);
    final ConfigurableApplicationContext context = app.run(ApiController.class, args);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                log.info("Bastion shutting down");
                Iterator<ActorRef> iterator = chains.iterator();
                while (iterator.hasNext())
                    iterator.next().tell(new StopMessage(), null);
                Thread.sleep(2000);
                context.stop();
                log.info("Bastion shutdown complete");
            } catch (Exception e) {
            }
        }
    });
}

From source file:io.fluo.cluster.WorkerApp.java

public static void main(String[] args) throws ConfigurationException, Exception {

    AppOptions options = new AppOptions();
    JCommander jcommand = new JCommander(options, args);

    if (options.displayHelp()) {
        jcommand.usage();//from  w w w. j a  v  a2s.co  m
        System.exit(-1);
    }

    Logging.init("worker", options.getFluoHome() + "/conf", "STDOUT");

    File configFile = new File(options.getFluoHome() + "/conf/fluo.properties");
    FluoConfiguration config = new FluoConfiguration(configFile);
    if (!config.hasRequiredWorkerProps()) {
        log.error("fluo.properties is missing required properties for worker");
        System.exit(-1);
    }
    Environment env = new Environment(config);

    YarnConfiguration yarnConfig = new YarnConfiguration();
    yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/core-site.xml"));
    yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/yarn-site.xml"));

    TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfig, env.getZookeepers());
    twillRunner.startAndWait();

    TwillPreparer preparer = twillRunner.prepare(new WorkerApp(options, config));

    // Add any observer jars found in lib observers
    File observerDir = new File(options.getFluoHome() + "/lib/observers");
    for (File f : observerDir.listFiles()) {
        String jarPath = "file:" + f.getCanonicalPath();
        log.debug("Adding observer jar " + jarPath + " to YARN app");
        preparer.withResources(new URI(jarPath));
    }

    TwillController controller = preparer.start();
    controller.start();

    while (controller.isRunning() == false) {
        Thread.sleep(2000);
    }
    env.close();
    System.exit(0);
}