Example usage for java.io BufferedReader close

List of usage examples for java.io BufferedReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:BufferedSocketClient.java

  public static void main(String args[]) throws Exception {
  Socket socket1;//from w w  w  .  j  a v  a2  s  .  co m
  int portNumber = 1777;
  String str = "initialize";

  socket1 = new Socket(InetAddress.getLocalHost(), portNumber);

  BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));

  PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);

  pw.println(str);

  while ((str = br.readLine()) != null) {
    System.out.println(str);
    pw.println("bye");

    if (str.equals("bye"))
      break;
  }

  br.close();
  pw.close();
  socket1.close();
}

From source file:math2605.gn_log.java

/**
 * @param args the command line arguments
 *//*from ww w . j av a  2  s .c  om*/
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix();
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix();
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());
}

From source file:math2605.gn_exp.java

/**
 * @param args the command line arguments
 *///  ww  w  .j  av  a2s  . c o  m
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix();
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix();
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());

}

From source file:math2605.gn_qua.java

/**
 * @param args the command line arguments
 *///  w  ww.j a v  a 2 s  .c  o  m
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix(pairs.size(), 1);
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix(pairs.size(), 3);
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());
}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *//*from ww  w .  ja v  a2 s.  co  m*/
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}

From source file:ui.pack.MyFrame.java

public static void main(String... args) throws IOException {
    //MyFrame mf= new MyFrame();
    HttpClient client = HttpClientBuilder.create().build();
    String url = "http://localhost:8080/students/all";
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    StringBuilder builder = new StringBuilder();
    while (true) {
        String line = bufferedReader.readLine();
        if (line == null) {
            break;
        } else {/*from  www  .  j a  v  a2s . c o  m*/
            builder.append(line);
        }
    }
    bufferedReader.close();
    String result = builder.toString();
    System.out.println(result);
    JSONArray arr = new JSONArray(result);
    System.out.println(arr.length());

    //client.
}

From source file:Converter.java

public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream(new File("input.txt"));
    BufferedReader in = new BufferedReader(new InputStreamReader(fis, "SJIS"));

    FileOutputStream fos = new FileOutputStream(new File("output.txt"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));

    int len = 80;
    char buf[] = new char[len];

    int numRead;//w  w w . j  a va  2  s.c  o  m
    while ((numRead = in.read(buf, 0, len)) != -1)
        out.write(buf, 0, numRead);
    out.close();
    in.close();
}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);/*from ww  w.j a  va 2  s . co  m*/
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception// w ww  .j  a  v a 2s .c o m
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main./*from www  . j a v a2s .co m*/
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}