Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

In this page you can find the example usage for java.io BufferedReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:UseConverters.java

public static void main(String[] args) {
    try {//from   w  w  w . j  a v  a2s .c o  m
        BufferedReader fromKanji = new BufferedReader(
                new InputStreamReader(new FileInputStream("kanji.txt"), "EUC_JP"));
        PrintWriter toSwedish = new PrintWriter(new OutputStreamWriter( // XXX
                // check
                // enco
                new FileOutputStream("sverige.txt"), "ISO8859_3"));

        // reading and writing here...
        String line = fromKanji.readLine();
        System.out.println("-->" + line + "<--");
        toSwedish.println(line);
        fromKanji.close();
        toSwedish.close();
    } catch (UnsupportedEncodingException exc) {
        System.err.println("Bad encoding" + exc);
        return;
    } catch (IOException err) {
        System.err.println("I/O Error: " + err);
        return;
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String pageAddr = "http://www.google.com/index.htm";
    URL url = new URL(pageAddr);
    String websiteAddress = url.getHost();

    String file = url.getFile();/*ww w . j  av  a  2s.c o m*/
    Socket clientSocket = new Socket(websiteAddress, 80);

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    OutputStreamWriter outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
    outWriter.write("GET " + file + " HTTP/1.0\r\n\n");
    outWriter.flush();
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    boolean more = true;
    String input;
    while (more) {
        input = inFromServer.readLine();
        if (input == null)
            more = false;
        else {
            out.write(input);
        }
    }
    out.close();
    clientSocket.close();
}

From source file:nbayes_mr.NBAYES_MR.java

public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
    // TODO code application logic here
    splitter("/home/hduser/hw4data.csv");

    //FileSystem hdfs=FileSystem.get(new Configuration());

    //System.out.println("1-----"+hdfs.getHomeDirectory());
    //Path inpdir=new Path(hdfs.getHomeDirectory().toString()+"/input");
    for (int i = 1; i <= 5; i++) {
        //hdfs.delete(inpdir,true);
        //FileUtils.cleanDirectory(new File());
        //hdfs.mkdirs(inpdir);
        //FileUtils.cleanDirectory(new File("/output"));
        //           for(int j=1;j<=5;j++){
        //              if(j!=i){
        //                 File source = new File("/home/hduser/data"+j+".txt");
        //                   File dest = new File("/input");
        //                   try {
        //                      
        //                      hdfs.copyFromLocalFile(new Path("/home/hduser/data"+j+".txt"),inpdir);
        //                      //FileUtils.copyFileToDirectory(source, dest);
        //                       //FileUtils.copyDirectory(source, dest);
        //                   } catch (IOException e) {
        //                       e.printStackTrace();
        //                   }
        //              }
        //           }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "kmeans");
        job.setJarByClass(NBAYES_MR.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumCombiner.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        FileInputFormat.setInputPaths(job, new Path("/input" + String.valueOf(i)));
        FileOutputFormat.setOutputPath(job, new Path("/output"));
        job.waitForCompletion(true);//from  www. j  ava 2 s  .  c o  m

        FileSystem fOpen = FileSystem.get(conf);
        Path outputPathReduceFile = new Path("/output/part-r-00000");
        BufferedReader reader = new BufferedReader(new InputStreamReader(fOpen.open(outputPathReduceFile)));
        String Line = reader.readLine();
        //System.out.println(Line);
        while (Line != null) {
            String[] split = Line.split("_");
            String belongs[] = split[0].split(":");
            //System.out.println(Line);
            if (belongs[0].equalsIgnoreCase("X")) {
                probxmap.put(belongs[1], Integer.parseInt(split[1].trim()));
            } else if (belongs[0].equalsIgnoreCase("H")) {
                probhmap.put(belongs[1], Integer.parseInt(split[1].trim()));
            } else if (belongs[0].equalsIgnoreCase("X|H")) {
                //System.out.println(belongs[1]);
                probxhmap.put(belongs[1], Integer.parseInt(split[1].trim()));
            } else {
                total = Integer.parseInt(split[1].trim());
            }
            //probmap.put(split[0], Integer.parseInt(split[1]));
            Line = reader.readLine();
        }
        deleteFolder(conf, "/output");
        test("/home/hduser/data" + i + ".txt");

    }
    double avg = 0.0;
    for (int i = 0; i < accuracy.size(); i++) {
        avg += accuracy.get(i);
    }
    System.out.println("Accuracy : " + avg * 100 / 5);

}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();//from   ww  w . j  a v  a 2  s .c  om
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.mcgill.networkdynamics.geoinference.evaluation.CrossValidationScorer.java

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

    if (args.length != 4) {
        System.out.println("java CVS predictions-dir/ " + "cv-gold-dir/ results.txt error-sample.tsv");
        return;//from w w  w . j a v a  2  s.co m
    }

    File predDir = new File(args[0]);
    File cvDir = new File(args[1]);

    TDoubleList errors = new TDoubleArrayList(10_000_000);
    TLongSet locatedUsers = new TLongHashSet(10_000_000);
    TLongSet allUsers = new TLongHashSet(10_000_000);
    TLongObjectMap<TDoubleList> userToErrors = new TLongObjectHashMap<TDoubleList>();

    TLongDoubleMap tweetIdToError = new TLongDoubleHashMap(10_000_000);
    TLongObjectMap<double[]> idToPredLoc = new TLongObjectHashMap<double[]>();

    int tweetsSeen = 0;
    int tweetsLocated = 0;

    BufferedReader cvBr = new BufferedReader(new FileReader(new File(cvDir, "folds.info.tsv")));
    for (String foldLine = null; (foldLine = cvBr.readLine()) != null;) {
        String[] cols = foldLine.split("\t");
        String foldName = cols[0];

        System.out.printf("Scoring results for fold %s%n", foldName);

        File foldPredictionsFile = new File(predDir, foldName + ".results.tsv.gz");

        File goldLocFile = new File(cvDir, foldName + ".gold-locations.tsv");

        if (foldPredictionsFile.exists()) {
            BufferedReader br = Files.openGz(foldPredictionsFile);
            for (String line = null; (line = br.readLine()) != null;) {
                String[] arr = line.split("\t");
                long id = Long.parseLong(arr[0]);
                idToPredLoc.put(id, new double[] { Double.parseDouble(arr[1]), Double.parseDouble(arr[2]) });
            }
            br.close();
        }

        System.out.printf("loaded predictions for %d tweets; " + "scoring predictions%n", idToPredLoc.size());

        BufferedReader br = new BufferedReader(new FileReader(goldLocFile));
        for (String line = null; (line = br.readLine()) != null;) {
            String[] arr = line.split("\t");
            long id = Long.parseLong(arr[0]);
            long userId = Long.parseLong(arr[1]);

            allUsers.add(userId);
            tweetsSeen++;

            double[] predLoc = idToPredLoc.get(id);
            if (predLoc == null)
                continue;

            tweetsLocated++;
            locatedUsers.add(userId);

            double[] goldLoc = new double[] { Double.parseDouble(arr[2]), Double.parseDouble(arr[3]) };

            double dist = Geometry.getDistance(predLoc, goldLoc);
            errors.add(dist);
            tweetIdToError.put(id, dist);

            TDoubleList userErrors = userToErrors.get(userId);
            if (userErrors == null) {
                userErrors = new TDoubleArrayList();
                userToErrors.put(userId, userErrors);
            }
            userErrors.add(dist);

        }
        br.close();
    }

    errors.sort();
    System.out.println("Num errors to score: " + errors.size());

    double auc = 0;
    double userCoverage = 0;
    double tweetCoverage = tweetsLocated / (double) tweetsSeen;
    double medianMaxUserError = Double.NaN;
    double medianMedianUserError = Double.NaN;

    if (errors.size() > 0) {
        auc = computeAuc(errors);
        userCoverage = locatedUsers.size() / ((double) allUsers.size());
        TDoubleList maxUserErrors = new TDoubleArrayList(locatedUsers.size());
        TDoubleList medianUserErrors = new TDoubleArrayList(locatedUsers.size());
        for (TDoubleList userErrors : userToErrors.valueCollection()) {
            userErrors.sort();
            maxUserErrors.add(userErrors.get(userErrors.size() - 1));
            medianUserErrors.add(userErrors.get(userErrors.size() / 2));
        }

        maxUserErrors.sort();
        medianMaxUserError = maxUserErrors.get(maxUserErrors.size() / 2);

        medianUserErrors.sort();
        medianMedianUserError = medianUserErrors.get(medianUserErrors.size() / 2);

        // Compute CDF
        int[] errorsPerKm = new int[MAX_KM];
        for (int i = 0; i < errors.size(); ++i) {
            int error = (int) (Math.round(errors.get(i)));
            errorsPerKm[error]++;
        }

        // The accumulated sum of errors per km
        int[] errorsBelowEachKm = new int[errorsPerKm.length];
        for (int i = 0; i < errorsBelowEachKm.length; ++i) {
            errorsBelowEachKm[i] = errorsPerKm[i];
            if (i > 0)
                errorsBelowEachKm[i] += errorsBelowEachKm[i - 1];
        }

        final double[] cdf = new double[errorsBelowEachKm.length];
        double dSize = errors.size(); // to avoid casting all the time
        for (int i = 0; i < cdf.length; ++i)
            cdf[i] = errorsBelowEachKm[i] / dSize;
    }

    PrintWriter pw = new PrintWriter(new File(args[2]));
    pw.println("AUC\t" + auc);
    pw.println("user coverage\t" + userCoverage);
    pw.println("tweet coverage\t" + tweetCoverage);
    pw.println("median-max error\t" + medianMaxUserError);
    pw.close();

    // Choose a random sampling of 10K tweets to pass on to the authors
    // here.        
    PrintWriter errorsPw = new PrintWriter(args[3]);
    TLongList idsWithErrors = new TLongArrayList(tweetIdToError.keySet());
    idsWithErrors.shuffle(new Random());
    // Choose the first 10K
    for (int i = 0, chosen = 0; i < idsWithErrors.size() && chosen < 10_000; ++i) {

        long id = idsWithErrors.get(i);
        double[] prediction = idToPredLoc.get(id);
        double error = tweetIdToError.get(id);
        errorsPw.println(id + "\t" + error + "\t" + prediction[0] + "\t" + prediction[1]);
        ++chosen;
    }
    errorsPw.close();
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

public static void main(String[] args) throws Exception {
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%BC%D0%B0%D1%87%D0%BE%D0%B2%D0%B5%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE/
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE-%D0%B8-%D0%B2-%D0%BF%D0%B5%D1%82/
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%B8-%D0%B2-%D1%87%D0%B5%D1%82%D0%B2%D1%8A%D1%80%D1%82%D0%B8%D1%8F/

    builder = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerAdapter())
            .registerTypeAdapter(String.class, new StringAdapter())
            .registerTypeAdapter(Action.class, new ActionAdapter()).setPrettyPrinting();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(FIBAJsonParser.class.getResourceAsStream("/games.txt")));
    String location = null;/* ww  w. jav a2 s . com*/
    while ((location = reader.readLine()) != null) {
        location = location.trim();
        try {
            readLocation(location);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /*
     readLocation("48965/13/13/23/68uR30BQLmzJM");
     readLocation("48965/13/15/86/78CJrCjRx5mh6");
     readLocation("48965/13/13/18/12pOKqzKs5nE");
     readLocation("48965/13/29/11/33upB2PIPn3MI");
            
     readLocation("48965/13/13/21/38Gqht27dPT1");
     readLocation("48965/13/15/84/999JtqK7Eao");
     readLocation("48965/13/29/07/66ODts76QU17A");
     */
}

From source file:Test.java

public static void main(String[] arstring) throws Exception {
        SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory
                .getDefault();//  ww w  .  j  a v a2  s.co m
        SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
        System.out.println("Waiting for a client ...");
        SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();

        SSLParameters parameters = sslSocket.getSSLParameters();
        parameters.setAlgorithmConstraints(new SimpleConstraints());

        AlgorithmConstraints constraints = parameters.getAlgorithmConstraints();
        System.out.println("Constraint: " + constraints);

        String endPoint = parameters.getEndpointIdentificationAlgorithm();
        System.out.println("End Point: " + endPoint);

        System.out.println("Local Supported Signature Algorithms");
        if (sslSocket.getSession() instanceof ExtendedSSLSession) {
            ExtendedSSLSession extendedSSLSession = (ExtendedSSLSession) sslSocket.getSession();
            String alogrithms[] = extendedSSLSession.getLocalSupportedSignatureAlgorithms();
            for (String algorithm : alogrithms) {
                System.out.println("Algortihm: " + algorithm);
            }
        }

        System.out.println("Peer Supported Signature Algorithms");
        if (sslSocket.getSession() instanceof ExtendedSSLSession) {
            String alogrithms[] = ((ExtendedSSLSession) sslSocket.getSession())
                    .getPeerSupportedSignatureAlgorithms();
            for (String algorithm : alogrithms) {
                System.out.println("Algortihm: " + algorithm);
            }
        }

        InputStream inputstream = sslSocket.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        SSLSession session = sslSocket.getHandshakeSession();
        if (session != null) {
            System.out.println("Last accessed: " + new Date(session.getLastAccessedTime()));
        }

        String string = null;
        while ((string = bufferedreader.readLine()) != null) {
            System.out.println(string);
            System.out.flush();
        }

    }

From source file:edu.mit.fss.examples.TDRSSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the
 * SaudiComsat federate objects and launches the associated graphical user
 * interface.//w  ww  . j  ava  2 s .co m
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(TDRSSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final TDRSSFederate federate = new TDRSSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    logger.debug("Loading TLE data from file.");
    final List<Component> panels = new ArrayList<Component>();
    for (String satName : Arrays.asList("TDRS 3", "TDRS 5", "TDRS 6", "TDRS 7", "TDRS 8", "TDRS 9", "TDRS 10",
            "TDRS 11")) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

            while (br.ready()) {
                if (br.readLine().matches(".*" + satName + ".*")) {
                    logger.debug("Found " + satName + " data.");

                    logger.trace("Adding " + satName + " supplier space system.");
                    SpaceSystem system = new SpaceSystem(satName, new TLE(br.readLine(), br.readLine()),
                            5123e3);
                    federate.addObject(system);

                    panels.add(new SpaceSystemPanel(federate, system));

                    try {
                        logger.trace("Setting inital time.");
                        federate.setInitialTime(system.getInitialState().getDate()
                                .toDate(TimeScalesFactory.getUTC()).getTime());
                    } catch (IllegalArgumentException | OrekitException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                    break;
                }
            }
            br.close();
        } catch (IllegalArgumentException | OrekitException | IOException e) {
            e.printStackTrace();
            logger.fatal(e);
        }
    }

    try {
        logger.trace("Adding WSGT ground station.");
        SurfaceSystem wsgt = new SurfaceSystem("WSGT",
                new GeodeticPoint(FastMath.toRadians(32.5007), FastMath.toRadians(-106.6086), 1474),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(wsgt);
        panels.add(new SurfaceSystemPanel(federate, wsgt));

        logger.trace("Adding STGT ground station.");
        SurfaceSystem stgt = new SurfaceSystem("STGT",
                new GeodeticPoint(FastMath.toRadians(32.5430), FastMath.toRadians(-106.6120), 1468),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(stgt);
        panels.add(new SurfaceSystemPanel(federate, stgt));

        logger.trace("Adding GRGT ground station.");
        SurfaceSystem grgt = new SurfaceSystem("GRGT",
                new GeodeticPoint(FastMath.toRadians(13.6148), FastMath.toRadians(144.8565), 142),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(grgt);
        panels.add(new SurfaceSystemPanel(federate, grgt));
    } catch (OrekitException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.debug("Launching the graphical user interface.");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel(panels));
                frame.pack();
                frame.setVisible(true);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("TDRSS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();
}

From source file:no.uib.tools.OnthologyHttpClient.java

public static void main(String[] args) {
    try {/*from  w ww  . jav  a 2  s. com*/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet getRequest = new HttpGet(
                "http://www.ebi.ac.uk/ols/api/ontologies/mod/terms/http%253A%252F%252Fpurl.obolibrary.org%252Fobo%252FMOD_00861/descendants?size=2002");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to get the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        FileWriter fw = new FileWriter("./mod.json");
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            fw.write(output);
        }

        fw.close();
        httpClient.close();

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:com.aestel.chemistry.openEye.fp.DistMatrix.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.tsv from FingerPrinter]");
    opt.setRequired(true);//from  w w w .j av  a 2 s. c o m
    options.addOption(opt);

    opt = new Option("o", true, "outpur file [.tsv ");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0)
        exitWithHelp(options);

    String file = cmd.getOptionValue("i");
    BufferedReader in = new BufferedReader(new FileReader(file));

    file = cmd.getOptionValue("o");
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    ArrayList<Fingerprint> fps = new ArrayList<Fingerprint>();
    ArrayList<String> ids = new ArrayList<String>();
    String line;
    while ((line = in.readLine()) != null) {
        String[] parts = line.split("\t");
        if (parts.length == 3) {
            ids.add(parts[0]);
            fps.add(new ByteFingerprint(parts[2]));
        }
    }
    in.close();

    out.print("ID");
    for (int i = 0; i < ids.size(); i++) {
        out.print('\t');
        out.print(ids.get(i));
    }
    out.println();

    for (int i = 0; i < ids.size(); i++) {
        out.print(ids.get(i));
        Fingerprint fp1 = fps.get(i);

        for (int j = 0; j <= i; j++) {
            out.printf("\t%.4g", fp1.tanimoto(fps.get(j)));
        }
        out.println();
    }
    out.close();

    System.err.printf("Done %d fingerprints in %.2gsec\n", fps.size(),
            (System.currentTimeMillis() - start) / 1000D);
}