Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {/*from ww w  . j  a  v  a 2 s  .  co m*/
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        FileInputStream fis = new FileInputStream("sometextfile.txt");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement createTable = connection.createStatement();
        createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)");
        String ins = "INSERT INTO source_code VALUES(?,?)";
        PreparedStatement statement = connection.prepareStatement(ins);

        statement.setString(1, "TryInputStream2");
        statement.setAsciiStream(2, fis, fis.available());

        int rowsUpdated = statement.executeUpdate();
        System.out.println("Rows affected: " + rowsUpdated);
        Statement getCode = connection.createStatement();
        ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code");
        BufferedReader reader = null;
        String input = null;

        while (theCode.next()) {
            reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream("source")));
            while ((input = reader.readLine()) != null) {
                System.out.println(input);
            }
        }
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:RestGetClient.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://localhost:10080/example/json/product/get");
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

    //if (response.getStatusLine().getStatusCode() != 200) {
    //   throw new RuntimeException("Failed : HTTP error code : "
    //      + response.getStatusLine().getStatusCode());
    //}// w  w w  .  ja v  a2 s. com

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

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();
}

From source file:HrefMatch.java

public static void main(String[] args) {
    try {/*from  w ww. j a  v a 2s  . c  o  m*/
        // get URL string from command line or use default
        String urlString;
        if (args.length > 0)
            urlString = args[0];
        else
            urlString = "http://java.sun.com";

        // open reader for URL
        InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());

        // read contents into string builder
        StringBuilder input = new StringBuilder();
        int ch;
        while ((ch = in.read()) != -1)
            input.append((char) ch);

        // search for all occurrences of pattern
        String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String match = input.substring(start, end);
            System.out.println(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (PatternSyntaxException e) {
        e.printStackTrace();
    }
}

From source file:com.rest.samples.getTipoCambioBanxico.java

public static void main(String[] args) {
    String url = "http://www.banxico.org.mx/tipcamb/llenarTiposCambioAction.do?idioma=sp";
    try {/* www .j a  v a  2s  .c o m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/5.0");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        HttpResponse res = hc.execute(request);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        Document doc = Jsoup.parse(result.toString());
        Element tipoCambioFix = doc.getElementById("FIX_DATO");
        System.out.println(tipoCambioFix.text());

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.aj.hangman.HangmanReq.java

public static void main(String[] args) {
    HangmanDict dictionary = new HangmanDict();

    try {//from w w  w .j a  v  a2 s  . c o  m
        BufferedReader input = new BufferedReader(new InputStreamReader(
                new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream()));
        String info = input.readLine();
        JSONParser parser = new JSONParser();

        Object obj;
        try {
            obj = parser.parse(info);
            JSONObject retJson = (JSONObject) obj;

            TOKEN = (String) retJson.get("token");
            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            PREM = REM;
            System.out.println("State:: " + STATE);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while ("ALIVE".equalsIgnoreCase(STATUS)) {
            // call make guess function, returns character
            guess = dictionary.makeGuess(STATE);
            System.out.println("Guessed:: " + guess);
            // call the url to update
            BufferedReader reInput = new BufferedReader(
                    new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu"
                            + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream()));

            // parse the url to get the updated value
            String reInfo = reInput.readLine();
            JSONParser reParser = new JSONParser();

            Object retObj = reParser.parse(reInfo);
            JSONObject retJson = (JSONObject) retObj;

            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            System.out.println("State:: " + STATE);
        }

        if ("DEAD".equalsIgnoreCase(STATUS)) {
            // print lost
            System.out.println("You LOOSE: DEAD");
        } else if ("FREE".equalsIgnoreCase(STATUS)) {
            // print free
            System.out.println("You WIN: FREE");
        }

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

}

From source file:com.linkedin.pinot.broker.broker.BrokerServerBuilderTest.java

public static void main(String[] args) throws Exception {
    PropertiesConfiguration config = new PropertiesConfiguration(
            new File(BrokerServerBuilderTest.class.getClassLoader().getResource("broker.properties").toURI()));
    final BrokerServerBuilder bld = new BrokerServerBuilder(config, null, null, null);
    bld.buildNetwork();/*  ww w .  j  a va 2  s .c o m*/
    bld.buildHTTP();
    bld.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                bld.stop();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String command = br.readLine();
        if (command.equals("exit")) {
            bld.stop();
        }
    }

}

From source file:net.officefloor.tutorial.javascriptapp.JavaScriptAppTest.java

/**
 * Allow running as application to manually test the JavaScript.
 *//*from   ww w.j  a  va 2s.c o m*/
public static void main(String[] arguments) throws Exception {
    WoofOfficeFloorSource.start();
    System.out.println("Press [enter] to exit");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    WoofOfficeFloorSource.stop();
}

From source file:cloudclient.Client.java

public static void main(String[] args) throws Exception {
    //Command interpreter
    CommandLineInterface cmd = new CommandLineInterface(args);

    String socket = cmd.getOptionValue("s");
    String Host_IP = socket.split(":")[0];
    int Port = Integer.parseInt(socket.split(":")[1]);
    String workload = cmd.getOptionValue("w");

    try {//  w  ww.j  av a2  s. c  o m
        // make connection to server socket 
        Socket client = new Socket(Host_IP, Port);

        InputStream inStream = client.getInputStream();
        OutputStream outStream = client.getOutputStream();
        PrintWriter out = new PrintWriter(outStream, true);
        BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

        System.out.println("Send tasks to server...");
        //Start clock
        long startTime = System.currentTimeMillis();

        //Batch sending tasks
        batchSendTask(out, workload);
        client.shutdownOutput();

        //Batch receive responses
        batchReceiveResp(in);

        //End clock
        long endTime = System.currentTimeMillis();
        double totalTime = (endTime - startTime) / 1e3;

        System.out.println("\nDone!");
        System.out.println("Time to execution = " + totalTime + " sec.");

        // close the socket connection
        client.close();

    } catch (IOException ioe) {
        System.err.println(ioe);
    }

}

From source file:JSON.JasonJSON.java

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

    URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json");
    //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground 
    //writes a perfectly formatted JSON file that is easy to read with Java.
    // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201");

    try {/*w w w .ja  v  a 2 s .com*/

        HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection();

        //          This part will read the data returned thru HTTP and load it into memory
        //          I have this code left over from my CIT260 project.
        InputStream stream = urlCon.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        // The next lines read certain parts of the JSON data and print it out on the screen
        //Creates the JSONObject object and loads the JSON file from the URLConnection
        //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something

        JSONObject json = new JSONObject(result.toString());

        JSONObject coloradoInfo = (JSONObject) json.get("current_observation");

        StringWriter out = new StringWriter();
        json.write(out);
        String jsonTxt = json.toString();
        System.out.print(jsonTxt);

        List<String> list = new ArrayList<>();
        JSONArray array = json.getJSONArray(jsonTxt);
        System.out.print(jsonTxt);

        // for (int i =0;i<array.length();i++){
        //list.add(array.getJSONObject(i).getString("current_observation"));
        //}

        String wunderGround = "Data downloaded from: " +

                coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: "
                + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: "
                + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: "
                + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: "
                + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: "
                + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string")
                + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: "
                + coloradoInfo.get("pressure_in");

        System.out.println("\nColorado Springs Weather:");
        System.out.println("____________________________________");
        System.out.println(wunderGround);

    } catch (IOException e) {
        System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString()
                + "\nERROR: " + e.toString());
    }

}

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {//from   w ww  .ja  v  a 2s .c o m
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}