Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

In this page you can find the example usage for java.io PrintWriter close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:csv.parser.CSVParser.java

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
    String file_to_parse;//from w w  w. j  ava 2  s.  c o m
    String[] val_array;
    file_to_parse = "./input/E-library-data-3.csv";
    //Build reader instance
    //Read CSV file
    CSVReader reader = new CSVReader(new FileReader(file_to_parse), ';', '"', 1);

    //Read all rows at once
    List<String[]> allRows = reader.readAll();

    //        Read CSV line by line and use the string array as you want
    for (String[] row : allRows) {
        for (int i = 0; i < row.length; i++) {
            //Removing all newlines, tabs and '&' characters(invalid XML character)
            row[i] = row[i].replaceAll("(\\r|\\n|\\r\\n)+", " ");
            row[i] = row[i].replaceAll(System.getProperty("line.separator"), "; ");
            row[i] = row[i].replaceAll("&", "and");
        }

        System.out.println(Arrays.toString(row));
    }
    //Get the input fields
    List<String[]> map = getMap();
    String[] field;
    //Numbering for folders, folderNum is incremented for each new file
    long folderNum;
    folderNum = 0;
    for (String[] row : allRows) {
        //Creating new folder
        File file1 = new File("./output//newdir//folder" + folderNum + "");
        file1.mkdirs();
        //Creating content file
        PrintWriter writer_content = new PrintWriter("./output//newdir//folder" + folderNum + "//contents",
                "UTF-16");
        //Creating metadata_lrmi.xml
        PrintWriter writer_lrmi = new PrintWriter(
                "./output//newdir//folder" + folderNum + "//metadata_lrmi.xml", "UTF-16");
        //Creating content.xml
        PrintWriter writer = new PrintWriter("./output//newdir//folder" + folderNum + "//content.xml",
                "UTF-16");
        writer.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer.println("<dublin_core schema=\"dc\">");
        writer_lrmi.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer_lrmi.println("<dublin_core shema=\"lrmi\">");
        for (int i = 0; i < row.length; i++) {
            //After snooping data, we have to change these setting for each new csv file, as the data fileds are many times mismatched
            //These if-else statements take care of mismatched steps.
            if (i == 43) {
                continue;
            } else if (i == 43) {
                field = map.get(42);
            } else if (i == 44) {
                field = map.get(43);
            } else if (i == 45 || i == 46) {
                continue;
            } else {
                field = map.get(i);
            }
            //Separate multiple values
            val_array = parseVal(row[i]);
            //                if (val_array.length == 0) {
            //                    continue;
            //                }
            PrintWriter useWriter = writer;
            if (field[0].equals("lrmi")) {
                useWriter = writer_lrmi;
            }
            switch (field.length) {
            case 2:
                writeXML(useWriter, field[1], "", val_array);
                break;
            case 3:
                writeXML(useWriter, field[1], field[2], val_array);
                break;
            default:

            }
        }
        folderNum++;
        writer.println("</dublin_core>");
        writer_lrmi.println("</dublin_core>");
        writer.close();
        writer_lrmi.close();
        writer_content.close();
    }
}

From source file:lambertmrev.LambertMRev.java

/**
 * @param args the command line arguments
 *///w  ww .j a va 2s .  c  o  m
public static void main(String[] args) {
    // Want to test the Lambert class so you can specify the number of revs for which to compute
    //System.out.print("this is the frames tutorial \n");
    try {
        Frame inertialFrame = FramesFactory.getEME2000();
        TimeScale utc = TimeScalesFactory.getTAI();
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, utc);
        double mu = 3.986004415e+14;

        double a = 24396159; // semi major axis in meters
        double e = 0.72831215; // eccentricity
        double i = Math.toRadians(7); // inclination
        double omega = Math.toRadians(180); // perigee argument
        double raan = Math.toRadians(261); // right ascension of ascending node
        double lM = 0; // mean anomaly

        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        //KeplerianPropagator kepler = new KeplerianPropagator(initialOrbit);

        // set geocentric positions
        Vector3D r1 = new Vector3D(-6.88999e3, 3.92763e4, 2.67053e3);
        Vector3D r2 = new Vector3D(-3.41458e4, 2.05328e4, 3.44315e3);
        Vector3D r1_site = new Vector3D(4.72599e3, 1.26633e3, 4.07799e3);
        Vector3D r2_site = new Vector3D(4.70819e3, 1.33099e3, 4.07799e3);

        // get the topocentric positions
        Vector3D top1 = Transform.geo2radec(r1.scalarMultiply(1000), r1_site.scalarMultiply(1000));
        Vector3D top2 = Transform.geo2radec(r2.scalarMultiply(1000), r2_site.scalarMultiply(1000));

        // time of flight in seconds
        double tof = 3 * 3600;

        // propagate to 0 and tof
        Lambert test = new Lambert();

        boolean cw = false;
        int multi_revs = 1;
        RealMatrix v1_mat;
        Random randomGenerator = new Random();

        PrintWriter out_a = new PrintWriter("out_java_a.txt");
        PrintWriter out_e = new PrintWriter("out_java_e.txt");
        PrintWriter out_rho1 = new PrintWriter("out_java_rho1.txt");
        PrintWriter out_rho2 = new PrintWriter("out_java_rho2.txt");

        // start the loop
        double A, Ecc, rho1, rho2, tof_hyp;

        long time1 = System.nanoTime();
        for (int ll = 0; ll < 1e6; ll++) {

            rho1 = top1.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top1.getZ() / 1000;
            rho2 = top2.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top2.getZ() / 1000;
            //tof_hyp = FastMath.abs(tof + 0.1*3600 * randomGenerator.nextGaussian());
            // from topo to geo
            Vector3D r1_hyp = Transform.radec2geo(top1.getX(), top1.getY(), rho1, r1_site);
            Vector3D r2_hyp = Transform.radec2geo(top2.getX(), top2.getY(), rho2, r2_site);
            //            System.out.println(r1_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(r2_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(tof/3600);
            test.lambert_problem(r1_hyp.scalarMultiply(1000), r2_hyp.scalarMultiply(1000), tof, mu, cw,
                    multi_revs);

            v1_mat = test.get_v1();

            Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
            //            System.out.println(v1);
            PVCoordinates rv1 = new PVCoordinates(r1_hyp.scalarMultiply(1000), v1);
            Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
            A = orbit_out.getA();
            Ecc = orbit_out.getE();

            //            System.out.println(ll + " - " +A);
            out_a.println(A);
            out_e.println(Ecc);
            out_rho1.println(rho1);
            out_rho2.println(rho2);
        }
        long time2 = System.nanoTime();
        long timeTaken = time2 - time1;

        out_a.close();
        out_e.close();
        out_rho1.close();
        out_rho2.close();

        System.out.println("Time taken " + timeTaken / 1000 / 1000 + " milli secs");

        // get the truth
        test.lambert_problem(r1.scalarMultiply(1000), r2.scalarMultiply(1000), tof, mu, cw, multi_revs);
        v1_mat = test.get_v1();
        Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
        PVCoordinates rv1 = new PVCoordinates(r1.scalarMultiply(1000), v1);
        Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
        //System.out.println(orbit_out.getA());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(LambertMRev.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.adobe.aem.demomachine.Json2Csv.java

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

    String inputFile1 = null;//from  w w  w.ja v a2 s.co m
    String inputFile2 = null;
    String outputFile = null;

    HashMap<String, String> hmReportSuites = new HashMap<String, String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("c", true, "Filename 1");
    options.addOption("r", true, "Filename 2");
    options.addOption("o", true, "Filename 3");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("c")) {
            inputFile1 = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("r")) {
            inputFile2 = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("o")) {
            outputFile = cmd.getOptionValue("o");
        }

        if (inputFile1 == null || inputFile1 == null || outputFile == null) {
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // List of customers and report suites for these customers
    String sInputFile1 = readFile(inputFile1, Charset.defaultCharset());
    sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

    // Processing the list of report suites for each customer
    try {

        JSONArray jCustomers = new JSONArray(sInputFile1.trim());
        for (int i = 0, size = jCustomers.length(); i < size; i++) {
            JSONObject jCustomer = jCustomers.getJSONObject(i);
            Iterator<?> keys = jCustomer.keys();
            String companyName = null;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("company")) {
                    companyName = jCustomer.getString(key);
                }
            }
            keys = jCustomer.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();

                if (key.equals("report_suites")) {
                    JSONArray jReportSuites = jCustomer.getJSONArray(key);
                    for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) {
                        hmReportSuites.put(jReportSuites.getString(j), companyName);
                        System.out.println(jReportSuites.get(j) + " for company " + companyName);
                    }

                }
            }
        }

        // Creating the out put file
        PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
        writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents"
                + "\",\"" + "Last Updated" + "\"");

        // Processing the list of SOLR collections
        String sInputFile2 = readFile(inputFile2, Charset.defaultCharset());
        sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

        JSONObject jResults = new JSONObject(sInputFile2.trim());
        JSONArray jCollections = jResults.getJSONArray("result");
        for (int i = 0, size = jCollections.length(); i < size; i++) {
            JSONObject jCollection = jCollections.getJSONObject(i);
            String id = null;
            String number = null;
            String lastupdate = null;

            Iterator<?> keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("_id")) {
                    id = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("noOfDocs")) {
                    number = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("latestUpdateDate")) {
                    lastupdate = jCollection.getString(key);
                }
            }

            Date d = new Date(Long.parseLong(lastupdate));
            System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + ","
                    + new SimpleDateFormat("MM-dd-yyyy").format(d));
            writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\""
                    + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\"");

        }

        writer.close();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.medicaid.mmis.util.DataLoader.java

/**
 * The main function, imports the files given as arguments.
 * // w  w  w  .  ja va  2 s .  com
 * @param args the file names
 * @throws IOException for read/write errors
 * @throws PortalServiceException for any other errors
 */
public static void main(String[] args) throws IOException, PortalServiceException {
    if (args.length != 2) {
        System.out.println("2 file path arguments are required.");
        return;
    }

    PropertyConfigurator.configure("log4j.properties");
    logger = Logger.getLogger(DataLoader.class);

    LookupServiceBean lookupBean = new LookupServiceBean();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load");
    EntityManager em = emf.createEntityManager();
    lookupBean.setEm(em);
    DataLoader loader = new DataLoader();
    loader.setLookup(lookupBean);

    SequenceGeneratorBean sequence = new SequenceGeneratorBean();
    sequence.setEm(em);

    ProviderEnrollmentServiceBean enrollmentBean = new ProviderEnrollmentServiceBean();
    enrollmentBean.setEm(em);
    enrollmentBean.setSequence(sequence);
    enrollmentBean.setLookupService(lookupBean);

    loader.setEnrollmentService(enrollmentBean);

    long processId = sequence.getNextValue("PROCESS_ID");
    System.out.println("Started process id " + processId);

    BufferedReader br = null;
    PrintWriter accepted = null;
    PrintWriter rejected = null;
    try {
        System.out.println("Processing file 1...");
        File success = new File("accepted_1_" + processId + ".txt");
        File failure = new File("rejected_1_" + processId + ".txt");
        success.createNewFile();
        failure.createNewFile();
        accepted = new PrintWriter(success);
        rejected = new PrintWriter(failure);
        br = new BufferedReader(new FileReader(args[0]));
        String line = null;
        int total = 0;
        int errors = 0;
        while ((line = br.readLine()) != null) {
            total++;
            try {
                em.getTransaction().begin();
                loader.readProviderFile(new ByteArrayInputStream(line.getBytes()));
                em.getTransaction().commit();
                accepted.println(line);
                logger.info("Commit row " + total);
            } catch (PortalServiceException e) {
                rejected.println(line);
                em.getTransaction().rollback();
                errors++;
                logger.error("Rollback row " + total + " :" + e.getMessage());
            }
        }

        accepted.flush();
        accepted.close();
        rejected.flush();
        rejected.close();
        br.close();
        System.out.println("Total records read: " + total);
        System.out.println("Total rejected: " + errors);

        System.out.println("Processing file 2...");
        success = new File("accepted_2_" + processId + ".txt");
        failure = new File("rejected_2_" + processId + ".txt");
        success.createNewFile();
        failure.createNewFile();
        accepted = new PrintWriter(success);
        rejected = new PrintWriter(failure);
        br = new BufferedReader(new FileReader(args[1]));
        line = null;
        total = 0;
        errors = 0;
        while ((line = br.readLine()) != null) {
            total++;
            try {
                em.getTransaction().begin();
                Map<String, OwnershipInformation> owners = loader
                        .readWS000EXT2OWNBEN(new ByteArrayInputStream(line.getBytes()));
                for (Map.Entry<String, OwnershipInformation> entry : owners.entrySet()) {
                    enrollmentBean.addBeneficialOwners(entry.getKey(), entry.getValue());
                }
                em.getTransaction().commit();
                accepted.println(line);
                logger.info("Commit row " + total);
            } catch (PortalServiceException e) {
                rejected.println(line);
                em.getTransaction().rollback();
                errors++;
                logger.error("Rollback row " + total + " :" + e.getMessage());
            }
        }
        accepted.flush();
        rejected.flush();
        System.out.println("Total records read: " + total);
        System.out.println("Total rejected: " + errors);

    } finally {
        if (br != null) {
            br.close();
        }
        if (accepted != null) {
            accepted.close();
        }
        if (rejected != null) {
            rejected.close();
        }
    }
}

From source file:com.galois.fiveui.HeadlessRunner.java

/**
 * @param args list of headless run description filenames
 * @throws IOException//from   w ww  . j  av a2s.co m
 * @throws URISyntaxException
 * @throws ParseException
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) throws IOException, URISyntaxException, ParseException {

    // Setup command line options
    Options options = new Options();
    Option help = new Option("h", "print this help message");
    Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file")
            .create("o");
    Option report = OptionBuilder.withArgName("report directory").hasArg()
            .withDescription("write HTML reports to given directory").create("r");
    options.addOption(output);
    options.addOption(report);
    options.addOption("v", false, "verbose output");
    options.addOption("vv", false, "VERY verbose output");
    options.addOption(help);

    // Parse command line options
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Command line option parsing failed.  Reason: " + e.getMessage());
        System.exit(1);
    }

    // Display help if requested
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("headless <input file 1> [<input file 2> ...]", options);
        System.exit(1);
    }

    // Set logging levels
    BasicConfigurator.configure();
    Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui");
    Logger rootLogger = Logger.getRootLogger();
    if (cmd.hasOption("v")) {
        fiveuiLogger.setLevel(Level.DEBUG);
        rootLogger.setLevel(Level.ERROR);
    } else if (cmd.hasOption("vv")) {
        fiveuiLogger.setLevel(Level.DEBUG);
        rootLogger.setLevel(Level.DEBUG);
    } else {
        fiveuiLogger.setLevel(Level.ERROR);
        rootLogger.setLevel(Level.ERROR);
    }

    // Setup output file if requested
    PrintWriter outStream = null;
    if (cmd.hasOption("o")) {
        String outfile = cmd.getOptionValue("o");
        try {
            outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile)));
        } catch (IOException e) {
            System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile"));
            System.exit(1);
        }
    } else {
        outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
    }

    // Setup HTML reports directory before the major work happens in case we
    // have to throw an exception.
    PrintWriter summaryFile = null;
    PrintWriter byURLFile = null;
    PrintWriter byRuleFile = null;
    if (cmd.hasOption("r")) {
        String repDir = cmd.getOptionValue("r");
        try {
            File file = new File(repDir);
            if (!file.exists()) {
                file.mkdir();
                logger.info("report directory created: " + repDir);
            } else {
                logger.info("report directory already exists!");
            }
            summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html"));
            byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html"));
            byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html"));
        } catch (IOException e) {
            System.err.println("could not open report directory / files for writing");
            System.exit(1);
        }
    }

    // Major work: process input files
    ImmutableList<Result> results = null;
    for (String in : cmd.getArgs()) {
        HeadlessRunDescription descr = HeadlessRunDescription.parse(in);
        logger.debug("invoking headless run...");
        BatchRunner runner = new BatchRunner();
        results = runner.runHeadless(descr);
        logger.debug("runHeadless returned " + results.size() + " results");
        // write results to the output stream as we go
        for (Result result : results) {
            outStream.println(result.toString());
        }
        outStream.flush();
    }
    outStream.close();

    // Write report files if requested
    if (cmd.hasOption("r") && results != null) {
        Reporter kermit = new Reporter(results);
        summaryFile.write(kermit.getSummary());
        summaryFile.close();
        byURLFile.write(kermit.getByURL());
        byURLFile.close();
        byRuleFile.write(kermit.getByRule());
        byRuleFile.close();
    }
}

From source file:edu.isi.karma.research.modeling.ModelLearner_LOD.java

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

    ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getDefault();
    contextParameters.setParameterValue(ContextParameter.USER_CONFIG_DIRECTORY, "/Users/mohsen/karma/config");

    OntologyManager ontologyManager = new OntologyManager(contextParameters.getId());
    File ff = new File(Params.ONTOLOGY_DIR);
    File[] files = ff.listFiles();
    if (files == null) {
        logger.error("no ontology to import at " + ff.getAbsolutePath());
        return;/*from ww w .j  ava2 s.co m*/
    }

    for (File f : files) {
        if (f.getName().endsWith(".owl") || f.getName().endsWith(".rdf") || f.getName().endsWith(".n3")
                || f.getName().endsWith(".ttl") || f.getName().endsWith(".xml")) {
            logger.info("Loading ontology file: " + f.getAbsolutePath());
            ontologyManager.doImport(f, "UTF-8");
        }
    }
    ontologyManager.updateCache();

    String outputPath = Params.OUTPUT_DIR;
    String graphPath = Params.GRAPHS_DIR;

    FileUtils.cleanDirectory(new File(graphPath));

    List<SemanticModel> semanticModels = ModelReader.importSemanticModelsFromJsonFiles(Params.MODEL_DIR,
            Params.MODEL_MAIN_FILE_EXT);

    ModelLearner_LOD modelLearner = null;

    boolean onlyGenerateSemanticTypeStatistics = false;
    boolean onlyUseOntology = false;
    boolean useCorrectType = false;
    int numberOfCandidates = 4;
    boolean onlyEvaluateInternalLinks = false;
    int maxPatternSize = 3;

    if (onlyGenerateSemanticTypeStatistics) {
        getStatistics(semanticModels);
        return;
    }

    String filePath = Params.RESULTS_DIR + "temp/";
    String filename = "";

    filename += "lod-results";
    filename += useCorrectType ? "-correct" : "-k=" + numberOfCandidates;
    filename += onlyUseOntology ? "-ontology" : "-p" + maxPatternSize;
    filename += onlyEvaluateInternalLinks ? "-internal" : "-all";
    filename += ".csv";

    PrintWriter resultFile = new PrintWriter(new File(filePath + filename));

    resultFile.println("source \t p \t r \t t \n");

    for (int i = 0; i < semanticModels.size(); i++) {
        //      for (int i = 0; i <= 10; i++) {
        //      int i = 1; {

        int newSourceIndex = i;
        SemanticModel newSource = semanticModels.get(newSourceIndex);

        logger.info("======================================================");
        logger.info(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        System.out.println(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        logger.info("======================================================");

        SemanticModel correctModel = newSource;
        List<ColumnNode> columnNodes = correctModel.getColumnNodes();

        List<Node> steinerNodes = new LinkedList<Node>(columnNodes);

        String graphName = graphPath + "lod" + Params.GRAPH_FILE_EXT;

        if (onlyUseOntology) {
            modelLearner = new ModelLearner_LOD(new GraphBuilder(ontologyManager, false), steinerNodes);
        } else if (new File(graphName).exists()) {
            // read graph from file
            try {
                logger.info("loading the graph ...");
                DirectedWeightedMultigraph<Node, DefaultLink> graph = GraphUtil.importJson(graphName);
                modelLearner = new ModelLearner_LOD(new GraphBuilderTopK(ontologyManager, graph), steinerNodes);
            } catch (Exception e) {
                e.printStackTrace();
                resultFile.close();
                return;
            }
        } else {
            logger.info("building the graph ...");
            // create and save the graph to file
            //            GraphBuilder_Popularity b = new GraphBuilder_Popularity(ontologyManager, 
            //                  Params.LOD_OBJECT_PROPERIES_FILE, 
            //                  Params.LOD_DATA_PROPERIES_FILE);
            GraphBuilder_LOD_Pattern b = new GraphBuilder_LOD_Pattern(ontologyManager, Params.PATTERNS_DIR,
                    maxPatternSize);
            modelLearner = new ModelLearner_LOD(b.getGraphBuilder(), steinerNodes);
        }

        long start = System.currentTimeMillis();

        List<SortableSemanticModel> hypothesisList = modelLearner.hypothesize(useCorrectType,
                numberOfCandidates);

        long elapsedTimeMillis = System.currentTimeMillis() - start;
        float elapsedTimeSec = elapsedTimeMillis / 1000F;

        List<SortableSemanticModel> topHypotheses = null;
        if (hypothesisList != null) {

            //            for (SortableSemanticModel sss : hypothesisList) {
            //               ModelEvaluation mmm = sss.evaluate(correctModel);
            //               System.out.println(mmm.getPrecision() + ", " + mmm.getRecall());
            //            }
            topHypotheses = hypothesisList.size() > 10 ? hypothesisList.subList(0, 10) : hypothesisList;
        }

        Map<String, SemanticModel> models = new TreeMap<String, SemanticModel>();

        ModelEvaluation me;
        models.put("1-correct model", correctModel);
        if (topHypotheses != null)
            for (int k = 0; k < topHypotheses.size(); k++) {

                SortableSemanticModel m = topHypotheses.get(k);

                me = m.evaluate(correctModel, onlyEvaluateInternalLinks, false);

                String label = "candidate " + k + "\n" +
                //                     (m.getSteinerNodes() == null ? "" : m.getSteinerNodes().getScoreDetailsString()) +
                        "link coherence:"
                        + (m.getLinkCoherence() == null ? "" : m.getLinkCoherence().getCoherenceValue()) + "\n";
                label += (m.getSteinerNodes() == null || m.getSteinerNodes().getCoherence() == null) ? ""
                        : "node coherence:" + m.getSteinerNodes().getCoherence().getCoherenceValue() + "\n";
                label += "confidence:" + m.getConfidenceScore() + "\n";
                label += m.getSteinerNodes() == null ? ""
                        : "mapping score:" + m.getSteinerNodes().getScore() + "\n";
                label += "cost:" + roundDecimals(m.getCost(), 6) + "\n" +
                //                        "-distance:" + me.getDistance() + 
                        "-precision:" + me.getPrecision() + "-recall:" + me.getRecall();

                models.put(label, m);

                if (k == 0) { // first rank model
                    System.out.println("precision: " + me.getPrecision() + ", recall: " + me.getRecall()
                            + ", time: " + elapsedTimeSec);
                    logger.info("precision: " + me.getPrecision() + ", recall: " + me.getRecall() + ", time: "
                            + elapsedTimeSec);
                    String s = newSource.getName() + "\t" + me.getPrecision() + "\t" + me.getRecall() + "\t"
                            + elapsedTimeSec;
                    resultFile.println(s);

                }
            }

        String outName = outputPath + newSource.getName() + Params.GRAPHVIS_OUT_DETAILS_FILE_EXT;

        GraphVizUtil.exportSemanticModelsToGraphviz(models, newSource.getName(), outName,
                GraphVizLabelType.LocalId, GraphVizLabelType.LocalUri, true, true);

    }

    resultFile.close();

}

From source file:com.zimbra.cs.account.AttributeManagerUtil.java

public static void main(String[] args) throws IOException, ServiceException {
    CliUtil.toolSetup();// w  ww .j ava  2  s .co  m
    CommandLine cl = parseArgs(args);

    if (!cl.hasOption('a'))
        usage("no action specified");
    String actionStr = cl.getOptionValue('a');
    Action action = null;
    try {
        action = Action.valueOf(actionStr);
    } catch (IllegalArgumentException iae) {
        usage("unknown action: " + actionStr);
    }

    AttributeManager am = null;
    if (action != Action.dump && action != Action.listAttrs) {
        if (!cl.hasOption('i'))
            usage("no input attribute xml files specified");
        am = new AttributeManager(cl.getOptionValue('i'));
        if (am.hasErrors()) {
            ZimbraLog.misc.warn(am.getErrors());
            System.exit(1);
        }
    }

    OutputStream os = System.out;
    if (cl.hasOption('o')) {
        os = new FileOutputStream(cl.getOptionValue('o'));
    }
    PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf8")));

    AttributeManagerUtil amu = new AttributeManagerUtil(am);

    switch (action) {
    case dump:
        LdapProv.getInst().dumpLdapSchema(pw);
        break;
    case generateDefaultCOSLdif:
        amu.generateDefaultCOSLdif(pw);
        break;
    case generateDefaultExternalCOSLdif:
        amu.generateDefaultExternalCOSLdif(pw);
        break;
    case generateGetters:
        amu.generateGetters(cl.getOptionValue('c'), cl.getOptionValue('r'));
        break;
    case generateGlobalConfigLdif:
        amu.generateGlobalConfigLdif(pw);
        break;
    case generateLdapSchema:
        if (!cl.hasOption('t')) {
            usage("no schema template specified");
        }
        amu.generateLdapSchema(pw, cl.getOptionValue('t'));
        break;
    case generateMessageProperties:
        amu.generateMessageProperties(cl.getOptionValue('r'));
        break;
    case generateProvisioning:
        amu.generateProvisioningConstants(cl.getOptionValue('r'));
        break;
    case generateSchemaLdif:
        amu.generateSchemaLdif(pw);
        break;
    case listAttrs:
        amu.listAttrs(pw, cl.getOptionValues('c'), cl.getOptionValues('n'), cl.getOptionValues('f'));
        break;
    }

    pw.close();
}

From source file:id3Crawler.java

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

    //Input for the directory to be searched.
    System.out.println("Please enter a directory: ");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();

    //Start a timer to calculate runtime
    startTime = System.currentTimeMillis();

    System.out.println("Starting scan...");

    //Files for output
    PrintWriter pw1 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Song.txt"));
    PrintWriter pw2 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Artist.txt"));
    PrintWriter pw3 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Album.txt"));
    PrintWriter pw4 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/PerformedBy.txt"));
    PrintWriter pw5 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/TrackOf.txt"));
    PrintWriter pw6 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/CreatedBy.txt"));

    //This is used for creating IDs for artists, songs, albums.
    int idCounter = 0;

    //This is used to prevent duplicate artists
    String previousArtist = " ";
    String currentArtist;/*from   w ww.  j a va 2 s . c  o  m*/
    int artistID = 0;

    //This is used to prevent duplicate albums
    String previousAlbum = " ";
    String currentAlbum;
    int albumID = 0;

    //This array holds valid extensions to iterate through
    String[] extensions = new String[] { "mp3" };

    //iterate through all files in a directory
    Iterator<File> it = FileUtils.iterateFiles(new File(input), extensions, true);
    while (it.hasNext()) {

        //open the next file
        File file = it.next();

        //instantiate an mp3file object with the opened file
        MP3 song = GetMP3(file);

        //pass the song through SongInfo and return the required information
        SongInfo info = new SongInfo(song);

        //This is used to prevent duplicate artists/albums
        currentArtist = info.getArtistInfo();
        currentAlbum = info.getAlbumInfo();

        //Append the song information to the end of a text file
        pw1.println(idCounter + "\t" + info.getTitleInfo());

        //This prevents duplicates of artists
        if (!(currentArtist.equals(previousArtist))) {
            pw2.println(idCounter + "\t" + info.getArtistInfo());
            previousArtist = currentArtist;
            artistID = idCounter;
        }

        //This prevents duplicates of albums
        if (!(currentAlbum.equals(previousAlbum))) {
            pw3.println(idCounter + "\t" + info.getAlbumInfo());
            previousAlbum = currentAlbum;
            albumID = idCounter;

            //This formats the IDs for a "CreatedBy" relationship table
            pw6.println(artistID + "\t" + albumID);
        }

        //This formats the IDs for a "PerformedBy" relationship table
        pw4.println(idCounter + "\t" + artistID);

        //This formats the IDs for a "TrackOf" relationship table
        pw5.println(idCounter + "\t" + albumID);

        idCounter++;
        songCounter++;

    }
    scanner.close();
    pw1.close();
    pw2.close();
    pw3.close();
    pw4.close();
    pw5.close();
    pw6.close();

    System.out.println("Scan took " + ((System.currentTimeMillis() - startTime) / 1000.0) + " seconds to scan "
            + songCounter + " items!");

}

From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("r", "ref-seq", true,
            "Trim points are given as positions in a reference sequence from this file");
    options.addOption("i", "inclusive", false, "Trim points are inclusive");
    options.addOption("l", "length", true, "Minimum length of sequence after trimming");
    options.addOption("f", "filled-ratio", true,
            "Minimum ratio of filled model positions of sequence after trimming");
    options.addOption("o", "out", true, "Write sequences to directory (default=cwd)");
    options.addOption("s", "stats", true, "Write stats to file");

    PrintWriter statsOut = new PrintWriter(new NullWriter());
    boolean inclusive = false;
    int minLength = 0;
    int minTrimmedLength = 0;
    int maxNs = 0;
    int maxTrimNs = 0;

    int trimStart = 0;
    int trimStop = 0;
    Sequence refSeq = null;/*from  w ww  . j  a v a2s .c o  m*/
    float minFilledRatio = 0;

    int expectedModelPos = -1;
    String[] inputFiles = null;
    File outdir = new File(".");
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("ref-seq")) {
            refSeq = readRefSeq(new File(line.getOptionValue("ref-seq")));
        }

        if (line.hasOption("inclusive")) {
            inclusive = true;
        }

        if (line.hasOption("length")) {
            minLength = Integer.valueOf(line.getOptionValue("length"));
        }

        if (line.hasOption("filled-ratio")) {
            minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio"));
        }

        if (line.hasOption("out")) {
            outdir = new File(line.getOptionValue("out"));
            if (!outdir.isDirectory()) {
                outdir = outdir.getParentFile();
                System.err.println("Output option is not a directory, using " + outdir + " instead");
            }
        }

        if (line.hasOption("stats")) {
            statsOut = new PrintWriter(line.getOptionValue("stats"));
        }

        args = line.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        trimStart = Integer.parseInt(args[0]);
        trimStop = Integer.parseInt(args[1]);
        inputFiles = Arrays.copyOfRange(args, 2, args.length);

        if (refSeq != null) {
            expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length();
            trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model);
            trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options);
        System.err.println("Error: " + e.getMessage());
    }

    System.err.println("Starting sequence trimmer");
    System.err.println("*  Input files:           " + Arrays.asList(inputFiles));
    System.err.println("*  Minimum Length:        " + minLength);
    System.err.println("*  Trim point inclusive?: " + inclusive);
    System.err.println("*  Trim points:           " + trimStart + "-" + trimStop);
    System.err.println("*  Min filled ratio:      " + minFilledRatio);
    System.err.println("*  refSeq:                "
            + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc()));

    Sequence seq;
    SeqReader reader;
    TrimStats stats;

    writeStatsHeader(statsOut);

    FastaWriter seqWriter;
    File in;
    for (String infile : inputFiles) {
        in = new File(infile);
        reader = new SequenceReader(in);
        seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName()));

        while ((seq = reader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop));
                continue;
            }

            stats = getStats(seq, trimStart, trimStop);
            boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio);
            writeStats(statsOut, seq.getSeqName(), stats, passed);
            if (passed) {
                seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases));
            }
        }

        reader.close();
        seqWriter.close();
    }

    statsOut.close();
}

From source file:microbiosima.SelectiveMicrobiosima.java

/**
 * @param args//from  w  ww  .j a v  a 2  s.  c o m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    int populationSize = 500;//Integer.parseInt(parameters[1]);
    int microSize = 1000;//Integer.parseInt(parameters[2]);
    int numberOfSpecies = 150;//Integer.parseInt(parameters[3]);
    int numberOfGeneration = 10000;
    int Ngene = 10;
    int numberOfObservation = 100;
    int numberOfReplication = 10;
    double Ngenepm = 5;
    double pctEnv = 0;
    double pctPool = 0;
    double msCoeff = 1;
    double hsCoeff = 1;
    boolean HMS_or_TMS = true;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe"
                    + " [default: 500 1000 150 10000 10 5]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n"
            + "  msCoeff            Parameter related to microbe selection strength\n"
            + "  hsCoeff            Parameter related to host selection strength\n"
            + "  HMS_or_TMS         String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n"
            + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 5) {
            System.out.println(
                    "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got "
                            + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            msCoeff = Double.parseDouble(pct_config[2]);
            hsCoeff = Double.parseDouble(pct_config[3]);
            if (pct_config[4].equals("HMS"))
                HMS_or_TMS = true;
            if (pct_config[4].equals("TMS"))
                HMS_or_TMS = false;
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }
            if (msCoeff < 1) {
                System.out.println(
                        "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff="
                                + msCoeff + ")! EXIT");
                System.exit(3);
            }
            if (hsCoeff < 1) {
                System.out.println(
                        "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff="
                                + hsCoeff + ")! EXIT");
                System.exit(3);
            }
            if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) {
                System.out.println(
                        "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS="
                                + pct_config[4] + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
            Ngene = Integer.parseInt(configs[4]);
            Ngenepm = Double.parseDouble(configs[5]);
            if (Ngenepm > Ngene) {
                System.out.println(
                        "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT");
                System.exit(3);
            }
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication)
            .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ")
            .append(Ngenepm).append("\n");
    System.out.println(sb.toString());

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }
    int[] fitnessToHost = new int[Ngene];
    int[] fitnessToMicrobe = new int[Ngene];

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix;
        if (HMS_or_TMS)
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt";
        else
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt";
        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {
            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));
            PrintWriter file7 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix)));
            PrintWriter file8 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix)));
            PrintWriter file9 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix)));
            PrintWriter file10 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix)));
            PrintWriter file11 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix)));
            PrintWriter file12 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix)));
            for (int i = 0; i < Ngene; i++) {
                fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1;
                fitnessToHost[i] = MathUtil.getNextInt(2) - 1;
            }
            MathUtil.setSeed(rep % numberOfReplication);
            SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm,
                    msCoeff, fitnessToHost, fitnessToMicrobe);
            MathUtil.setSeed();
            SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize,
                    pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    //file1.print(population.gammaDiversity(false));
                    //file2.print(population.alphaDiversity(false));
                    //file1.print("\t");
                    //file2.print("\t");
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    //file3.print(population.betaDiversity(true));
                    //file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                    file7.print(population.averageHostFitness());
                    file7.print("\t");
                    file7.println(population.varianceHostFitness());
                    file8.println(population.cosOfMH());
                    file9.println(population.printOutHFitness());
                    file10.println(population.printOutMFitness());
                    file11.println(population.printBacteriaContents());
                }
                population.getNextGen();
            }
            for (SelectiveIndividual host : population.getIndividuals()) {
                file12.println(host.printBacteriaContents());
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
            file7.close();
            file8.close();
            file9.close();
            file10.close();
            file11.close();
            file12.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}