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:com.kynetx.ParseRuleset.java

public static void main(String[] args) throws Exception {
    File f = new File(args[0]);
    int notparsed = 0;
    int parsed = 0;

    File[] files = null;/*from   w w w .  j  av  a  2  s. c o m*/
    if (f.isDirectory()) {
        files = f.listFiles();
    } else {
        files = new File[1];
        files[0] = new File(args[0]);
    }
    for (int i = 0; i < files.length; i++) {
        File thefile = files[i];
        long start = System.currentTimeMillis();
        boolean skipfile = false;
        for (int ii = 0; ii < ignore.length; ii++) {
            if (thefile.getCanonicalPath().indexOf(ignore[ii] + ".krl") > 0) {
                skipfile = true;
                break;
            }
        }
        if (thefile.length() == 0 || thefile.length() == 31 || thefile.length() == 162 || skipfile) {
            notparsed = notparsed + 1;
            //               System.out.println("Skipping: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            //               System.out.println("Skipping " + thefile);
            continue;
        }
        parsed = parsed + 1;
        try {
            ANTLRFileStream input = new ANTLRFileStream(thefile.getCanonicalPath());
            com.kynetx.RuleSetLexer lexer = new com.kynetx.RuleSetLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            com.kynetx.RuleSetParser parser = new com.kynetx.RuleSetParser(tokens);
            parser.ruleset();
            JSONObject js = new JSONObject(parser.rule_json);
            if (parser.parse_errors.size() > 0) {
                for (int ii = 0; ii < parser.parse_errors.size(); ii++) {
                    System.err
                            .println("ERROR FOUND " + parser.parse_errors.get(ii) + " - " + thefile.toString());
                }
            }
            //               System.out.println("Parsed: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            //System.out.println(unescapeUnicode(js.toString()));
            System.out.println(js.toString());
            //System.out.println("=============");
            //System.out.println(js.toString());
        } catch (Exception e) {
            //               System.out.println("Error: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            System.out.println("Error " + thefile + " " + e.getMessage());
            e.printStackTrace();
        }
    }
    //         System.out.println("Not Parsed " + notparsed);
    //         System.out.println("Parsed " + parsed);

}

From source file:com.tonygalati.sprites.SpriteGenerator.java

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

    //        if (args.length != 3)
    //        {// w w  w .j a v a  2 s  .  c  o  m
    //           System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n");
    //           System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n");
    //           System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n");
    //           System.out.print("most browsers.\n\n");
    //           return;
    //        }

    //        Integer margin = Integer.parseInt(args[1]);
    Integer margin = Integer.parseInt("1");
    String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png";
    SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator();

    ClassLoader classLoader = SpriteGenerator.class.getClassLoader();
    URL folderPath = classLoader.getResource(NAIC_SMALL_ICON);
    if (folderPath != null) {
        File imageFolder = new File(folderPath.getPath());

        // Read images
        ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
        Integer yCoordinate = null;

        for (File f : imageFolder.listFiles()) {
            if (f.isFile()) {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

                if (ext.equals("png")) {
                    System.out.println("adding file " + fileName);
                    BufferedImage image = ImageIO.read(f);
                    imageList.add(image);

                    if (yCoordinate == null) {
                        yCoordinate = 0;
                    } else {
                        yCoordinate += (image.getHeight() + margin);
                    }

                    // add to cssGenerator
                    cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate);
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList) {
            totalHeight += image.getHeight() + margin;

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(),
                totalHeight, maxWidth);

        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList) {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight() + margin;
        }

        System.out.format("Writing sprite: %s%n", spriteFile);
        ImageIO.write(sprite, "png", new File(spriteFile));
        File cssFile = cssGenerator.getFile(spriteFile);
        System.out.println(cssFile.getAbsolutePath() + " created");
    } else {
        System.err.println("Could not find folder: " + NAIC_SMALL_ICON);

    }

}

From source file:com.nohowdezign.gcpmanager.Main.java

public final static void main(String[] args) {
    //Remove old log, it does not need to be there anymore.
    File oldLog = new File("./CloudPrintManager.log");

    if (oldLog.exists()) {
        oldLog.delete();//w  ww. j a  v a  2  s  . c o  m
    }

    //Create a file reader for the props file
    Reader propsStream = null;
    try {
        propsStream = new FileReader("./props.json");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    PrintManagerProperties props = null;
    if (propsStream != null) {
        props = gson.fromJson(propsStream, PrintManagerProperties.class);
    } else {
        logger.error("Property file does not exist. Please create one.");
    }

    //Set the variables to what is in the props file
    String email = props.getEmail();
    String password = props.getPassword();
    String printerId = props.getPrinterId();
    amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob();
    timeRestraintsForPrinter = props.getTimeRestraintsForPrinter();

    JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays();

    //AuthenticationManager authenticationManager = new AuthenticationManager();
    //authenticationManager.setPasswordToUse(props.getAdministrativePassword());
    //authenticationManager.initialize(1337); //Start the authentication manager on port 1337

    try {
        cloudPrint.connect(email, password, "cloudprintmanager-1.0");
    } catch (CloudPrintAuthenticationException e) {
        logger.error(e.getMessage());
    }

    //TODO: Get a working website ready
    //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer");
    //adminConsole.start();

    Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager");
    printJobManager.start();

    try {
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            logger.error("Your operating system is not supported. Please switch to linux ya noob.");
            System.exit(1);
        } else {
            PrinterManager printerManager = new PrinterManager(cloudPrint);

            File cupsPrinterDir = new File("/etc/cups/ppd");

            if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) {
                for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) {
                    //Init all of the CUPS printers in the manager
                    printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName());
                }
            } else {
                logger.error("Please run this with a higher access level.");
                System.exit(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            getPrintingJobs(printerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:DIA_Umpire_To_Skyline.DIA_Umpire_To_Skyline.java

/**
 * @param args the command line arguments
 *//*from  w ww . java 2  s .  c  o m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire_To_Skyline (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path NoThreads");
        System.out.println("command : java -jar -Xmx20G DIA_Umpire_To_Skyline.jar Path [Option]\n");
        System.out.println("\nOptions");
        System.out.println("\t-t\tNo. of threads, Ex: -t4 (using four threads, default value)");
        System.out.println(
                "\t-cP\tPath of msconvert.exe for mzXML conversion, Ex: -cP (using four threads, default value)");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.DEBUG);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_to_skyline.log");
    } catch (Exception e) {
        System.out.println("Logger initialization failed");
    }

    Logger.getRootLogger().info("Path:" + args[0]);
    String msconvertpath = "C:/inetpub/tpp-bin/msconvert";

    String WorkFolder = args[0];
    int NoCPUs = 4;

    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            if (args[i].startsWith("-cP")) {
                msconvertpath = args[i].substring(3);
                Logger.getRootLogger().info("MSConvert path: " + msconvertpath);
            }
            if (args[i].startsWith("-t")) {
                NoCPUs = Integer.parseInt(args[i].substring(2));
                Logger.getRootLogger().info("No. of threads: " + NoCPUs);
            }
        }
    }

    HashMap<String, File> AssignFiles = new HashMap<>();

    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("Path: " + folder.getAbsolutePath() + " cannot be found.");
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile() && fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile() && fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        ExecutorService executorPool = null;
        executorPool = Executors.newFixedThreadPool(3);

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            FileThread thread = new FileThread(mzXMLFile, NoCPUs, msconvertpath);
            executorPool.execute(thread);
        }
        executorPool.shutdown();
        try {
            executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Logger.getRootLogger().info("interrupted..");
        }
    } catch (Exception e) {
        Logger.getRootLogger().error(e.getMessage());
        throw e;
    }
    Logger.getRootLogger().info("Job done");
    Logger.getRootLogger().info(
            "=================================================================================================");

}

From source file:net.myrrix.online.eval.ParameterOptimizer.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.err.println(/*  www  . j ava2 s.  c  o m*/
                "Usage: dataDirectory numSteps evaluationPercentage property=min:max [property2=min2:max2 ...]");
        return;
    }

    final File dataDir = new File(args[0]);
    Preconditions.checkArgument(dataDir.exists() && dataDir.isDirectory(), "Not a directory: %s", dataDir);
    Preconditions.checkArgument(dataDir.listFiles().length > 0, "No files in: %s", dataDir);
    int numSteps = Integer.parseInt(args[1]);
    Preconditions.checkArgument(numSteps >= 2, "# steps must be at least 2: %s", numSteps);
    final double evaluationPercentage = Double.parseDouble(args[2]);
    Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0,
            "evaluationPercentage must be in (0,1]: %s", evaluationPercentage);

    Map<String, ParameterRange> parameterRanges = Maps.newHashMapWithExpectedSize(args.length);
    for (int i = 3; i < args.length; i++) {
        String[] propValue = EQUALS.split(args[i]);
        String systemProperty = propValue[0];
        String[] minMax = COLON.split(propValue[1]);
        ParameterRange range;
        try {
            int min = Integer.parseInt(minMax[0]);
            int max = Integer.parseInt(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        } catch (NumberFormatException ignored) {
            double min = Double.parseDouble(minMax[0]);
            double max = Double.parseDouble(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        }
        parameterRanges.put(systemProperty, range);
    }

    Callable<Number> evaluator = new Callable<Number>() {
        @Override
        public Number call() throws IOException, TasteException, InterruptedException {
            MyrrixIRStatistics stats = (MyrrixIRStatistics) new PrecisionRecallEvaluator().evaluate(dataDir,
                    0.9, evaluationPercentage, null);
            return stats == null ? null : stats.getMeanAveragePrecision();
        }
    };

    ParameterOptimizer optimizer = new ParameterOptimizer(parameterRanges, numSteps, evaluator, false);
    Map<String, Number> optimalValues = optimizer.findGoodParameterValues();
    System.out.println(optimalValues);
}

From source file:com.siva.filewritterprogram.Mp3FileWritterTool.java

public static void main(String[] args) {
    File directory = new File("D:\\Siva\\Entertainment\\EvergreenHits");

    FileFilter filter = new FileFilter() {
        @Override/* w  ww .j  a va 2  s.  co m*/
        public boolean accept(File file) {
            if (file.getName().endsWith(".mp3")) {
                return true;
            } else {
                return false;
            }
        }
    };
    File[] subdirs = directory.listFiles();
    for (File subDir : subdirs) {
        try {
            System.out.println("Going to read files under : " + subDir);
            if (subDir.isDirectory()) {
                File[] files = subDir.listFiles(filter);
                if (files != null) {
                    for (File file : files) {
                        FileUtils.copyFileToDirectory(file, new File(directory.getPath() + "\\toTransfer"));
                    }
                } else {
                    System.out.println("There are no songs inside. [" + subDir.getName() + "]");
                }
            } else {
                System.out.println("Not a directory. [" + subDir.getName() + "]");
            }
        } catch (IOException ex) {
            Logger.getLogger(Mp3FileWritterTool.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:mujava.cli.testnew.java

public static void main(String[] args) throws IOException {
    testnewCom jct = new testnewCom();
    String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" };
    new JCommander(jct, args);

    muJavaHomePath = Util.loadConfig();
    // muJavaHomePath= "/Users/dmark/mujava";

    // check if debug mode
    if (jct.isDebug() || jct.isDebugMode()) {
        Util.debug = true;//ww  w  . j  av  a  2s.  c  om
    }
    System.out.println(jct.getParameters().size());
    sessionName = jct.getParameters().get(0); // set first parameter as the
    // session name

    ArrayList<String> srcFiles = new ArrayList<>();

    for (int i = 1; i < jct.getParameters().size(); i++) {
        srcFiles.add(jct.getParameters().get(i)); // retrieve all src file
        // names from parameters
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if the session is new or not
    if (fileNameList.contains(sessionName)) {
        Util.Error("Session already exists.");
    } else {
        // create sub-directory for the session
        setupSessionDirectory(sessionName);

        // move src files into session folder
        for (String srcFile : srcFiles) {
            // new (dir, name)
            // check abs path or not

            // need to check if srcFile has .java at the end or not
            if (srcFile.length() > 5) {
                if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java
                {
                    // delete .java, e.g. make it cal
                    srcFile = srcFile.substring(0, srcFile.length() - 5);
                }
            }

            File source = new File(srcFile + ".java");

            if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java
            {
                source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java");

            }

            File desc = new File(muJavaHomePath + "/" + sessionName + "/src");
            FileUtils.copyFileToDirectory(source, desc);

            // compile src files
            // String srcName = "t";
            boolean result = compileSrc(srcFile);
            if (result)
                Util.Print("Session is built successfully.");
        }

    }

    // System.exit(0);
}

From source file:net.cloudkit.relaxation.CaptchaTest.java

public static void main(String[] args) {

    // System.out.println(Color.WHITE.getRGB());

    try {/*from w  ww. j ava2s. co  m*/
        File fileDirectory = new File("D:\\customs\\");
        File[] files = fileDirectory.isDirectory() ? fileDirectory.listFiles() : new File[0];
        for (int a = 0; a < files.length; a++) {
            if (files[a].isDirectory())
                continue;
            InputStream inputStream = new FileInputStream(files[a]);
            BufferedImage bi = ImageIO.read(inputStream);
            clearBorder(bi);
            clearNoise(bi);
            // List<BufferedImage> subImgs = splitImage(bi);

            /*
            for (int i = 0; i < subImgs.size(); i++) {
            File imageFile = new File("D:\\images\\" + i + ".gif");
            ImageIO.write(subImgs.get(i), "gif", imageFile);
            }
            */

            FileOutputStream fos = new FileOutputStream("D:\\images\\"
                    + files[a].getName().substring(0, files[a].getName().indexOf(".")) + a + ".jpg");
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
            encoder.encode(bi);
            fos.close();

            // File file2 = new File("D:\\images\\" + a + "_" + files[a].getName());
            // ImageIO.write(bi, "gif", file2);
        }

        /*
        CloseableHttpClient httpclient = HttpClients.createDefault();
        for (int i = 0; i < 1000; i++) {
        HttpGet httpGet = new HttpGet("http://query.customs.gov.cn/MNFTQ/Image.aspx?" + Math.random() * 1000);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
                
            InputStream input = entity1.getContent();
            File storeFile = new File("D:\\customs\\customs"+ i +".jpg");
            FileOutputStream output = new FileOutputStream(storeFile);
            IOUtils.copy(input, output);
            output.close();
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
        }
        */
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

public static void main(String[] args) {
    try {/*  w w w . ja  v a 2 s.co  m*/
        String host = null;
        String userId = null;
        String password = null;
        if (args != null && args.length == 3) {
            host = args[0];
            userId = args[1];
            password = args[2];
            if (host.length() == 0 || userId.length() == 0 || password.length() == 0) {
                System.out.println("host, userId and password are required");
                System.exit(1);
            }
        } else {
            System.out.println("Usage: PageLoader host userId password");
            System.exit(1);
        }

        File folder = getFileFromResourceFolder(pageFolder);
        if (folder != null) {
            httpclient = HttpClients.createDefault();
            // login as owner here
            login(host, userId, password);
            getPageMap(host);

            File[] listOfFiles = folder.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                loadPageFile(host, listOfFiles[i]);
            }
            httpclient.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:com.github.lgi2p.obirs.utils.JSONConverter.java

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

    String annotdir = "/data/toxnuc/toxnuc_annots_5_11_14/annots";
    String annotsIndex = "/data/toxnuc/toxnuc_annots_5_11_14.json";

    File folder = new File(annotdir);
    File[] listOfFiles = folder.listFiles();

    PrintWriter printWriter = new PrintWriter(annotsIndex);

    int i = 0;/*  w ww .  j  a  v a2 s. co m*/
    for (File file : listOfFiles) {
        if (file.isFile()) {
            System.out.println(file.getPath());
            String title = file.getName();
            String href = file.getPath();
            String json = toJSONindexFormat(i, title, Utils.readFileAsString(file), href);
            i++;

            printWriter.println(json);
        }
    }
    printWriter.close();
    System.out.println("consult: " + annotsIndex);
}