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:io.s4.util.AvroSchemaSupplementer.java

public static void main(String args[]) {
    if (args.length < 1) {
        System.err.println("No schema filename specified");
        System.exit(1);/* ww  w  .j  a v  a2s  .  c  o  m*/
    }

    String filename = args[0];
    FileReader fr = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    try {
        if (filename == "-") {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
        } else {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
        }

        String inputLine = "";
        StringBuffer jsonBuffer = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            jsonBuffer.append(inputLine);
        }

        JSONObject jsonRecord = new JSONObject(jsonBuffer.toString());

        JSONObject keyPathElementSchema = new JSONObject();
        keyPathElementSchema.put("name", "KeyPathElement");
        keyPathElementSchema.put("type", "record");

        JSONArray fieldsArray = new JSONArray();
        JSONObject fieldRecord = new JSONObject();
        fieldRecord.put("name", "index");
        JSONArray typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyName");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);

        keyPathElementSchema.put("fields", fieldsArray);

        JSONObject keyInfoSchema = new JSONObject();
        keyInfoSchema.put("name", "KeyInfo");
        keyInfoSchema.put("type", "record");

        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "fullKeyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPathElementList");
        JSONObject typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyPathElementSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        keyInfoSchema.put("fields", fieldsArray);

        JSONObject partitionInfoSchema = new JSONObject();
        partitionInfoSchema.put("name", "PartitionInfo");
        partitionInfoSchema.put("type", "record");
        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "partitionId");
        typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundKey");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundValue");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyInfoList");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyInfoSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        partitionInfoSchema.put("fields", fieldsArray);

        fieldRecord = new JSONObject();
        fieldRecord.put("name", "S4__PartitionInfo");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", partitionInfoSchema);
        fieldRecord.put("type", typeRecord);

        fieldsArray = jsonRecord.getJSONArray("fields");
        fieldsArray.put(fieldRecord);

        System.out.println(jsonRecord.toString(3));
    } catch (Exception ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
        if (isr != null)
            try {
                isr.close();
            } catch (Exception e) {
            }
        if (fr != null)
            try {
                fr.close();
            } catch (Exception e) {
            }
    }
}

From source file:net.socket.bio.TimeClient.java

/**
 * @param args/*www .jav  a  2 s .c om*/
 */
public static void main(String[] args) {

    int port = 8089;
    if (args != null && args.length > 0) {

        try {
            port = Integer.valueOf(args[0]);
        } catch (NumberFormatException e) {
            // 
        }

    }
    Socket socket = null;
    BufferedReader in = null;
    PrintWriter out = null;
    try {
        socket = new Socket("127.0.0.1", port);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
        out.println("QUERY TIME ORDER");
        out.println("QUERY TIME ORDER");
        String test = StringUtils.repeat("hello tcp", 1000);
        out.println(test);
        System.out.println("Send order 2 server succeed.");
        String resp = in.readLine();
        System.out.println("Now is : " + resp);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(socket);
    }
}

From source file:icevaluation.BingAPIAccess.java

public static void main(String[] args) {
    String searchText = "arts site:wikipedia.org";
    searchText = searchText.replaceAll(" ", "%20");
    // String accountKey="jTRIJt9d8DR2QT/Z3BJCAvY1BfoXj0zRYgSZ8deqHHo";
    String accountKey = "JfeJSA3x6CtsyVai0+KEP0A6CYEUBT8VWhZmm9CS738";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    URL url;//from  w  ww. j  ava  2 s .c  om
    try {
        url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27"
                + searchText + "%27&$format=JSON");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        System.out.println("Output from Server .... \n");
        //write json to string sb
        int c = 0;
        if ((output = br.readLine()) != null) {
            System.out.println("Output is: " + output);
            sb.append(output);
            c++;
            //System.out.println("C:"+c);

        }

        conn.disconnect();
        //find webtotal among output      
        int find = sb.indexOf("\"WebTotal\":\"");
        int startindex = find + 12;
        System.out.println("Find: " + find);

        int lastindex = sb.indexOf("\",\"WebOffset\"");

        System.out.println(sb.substring(startindex, lastindex));

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:listfiles.ListFiles.java

/**
 * @param args the command line arguments
 *//*from w  w  w.  ja  v  a2  s  . co m*/
public static void main(String[] args) {
    // TODO code application logic here
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String folderPath = "";
    String fileName = "DirectoryFiles.xlsx";

    try {
        System.out.println("Folder path :");
        folderPath = reader.readLine();
        //System.out.println("Output File Name :");
        //fileName = reader.readLine();

        XSSFWorkbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(folderPath + "\\" + fileName);
        XSSFSheet sheet1 = wb.createSheet("Files");
        int row = 0;
        Stream<Path> stream = Files.walk(Paths.get(folderPath));
        Iterator<Path> pathIt = stream.iterator();
        String ext = "";

        while (pathIt.hasNext()) {
            Path filePath = pathIt.next();
            Cell cell1 = checkRowCellExists(sheet1, row, 0);
            Cell cell2 = checkRowCellExists(sheet1, row, 1);
            row++;
            ext = FilenameUtils.getExtension(filePath.getFileName().toString());
            cell1.setCellValue(filePath.getFileName().toString());
            cell2.setCellValue(ext);

        }
        sheet1.autoSizeColumn(0);
        sheet1.autoSizeColumn(1);

        wb.write(fileOut);
        fileOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Program Finished");
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;//from w ww . j  a  va2  s. com
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:BufferedSocketClient.java

public static void main(String args[]) throws Exception {
        int cTosPortNumber = 1777;
        String str;//from  w  ww. ja  v a 2s .  c om

        ServerSocket servSocket = new ServerSocket(cTosPortNumber);
        System.out.println("Waiting for a connection on " + cTosPortNumber);

        Socket fromClientSocket = servSocket.accept();
        PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);

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

        while ((str = br.readLine()) != null) {
            System.out.println("The message: " + str);

            if (str.equals("bye")) {
                pw.println("bye");
                break;
            } else {
                str = "Server returns " + str;
                pw.println(str);
            }
        }
        pw.close();
        br.close();

        fromClientSocket.close();
    }

From source file:comparetopics.CompareTwoGroupTopics.java

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("please input the path for File1: ");
    String filepath1 = sc.nextLine();
    System.out.println("please input the path for File2: ");
    String filepath2 = sc.nextLine();

    try {// w  w  w.  ja v a  2s .  co m
        File file1 = new File(filepath1);
        File file2 = new File(filepath2);
        System.out.println("File1: " + filepath1);
        System.out.println("File2: " + filepath2);

        if (!file1.exists()) {
            System.out.println("File1 isn't exist");
        } else if (!file2.exists()) {
            System.out.println("File2 isn't exist");
        } else {
            try (InputStream in1 = new FileInputStream(file1.getPath());
                    BufferedReader reader1 = new BufferedReader(new InputStreamReader(in1))) {

                String line1 = null;
                int lineNr1 = -1;
                while ((line1 = reader1.readLine()) != null) {
                    ++lineNr1;

                    int lineNr2 = -1;
                    String line2 = null;
                    try (InputStream in2 = new FileInputStream(file2.getPath());
                            BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2))) {
                        while ((line2 = reader2.readLine()) != null) {
                            ++lineNr2;
                            compareTwoGroups(line1, line2, lineNr1, lineNr2);
                        }
                    }
                    System.out.println();
                }
            }
        }

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

}

From source file:httpclientsample.HttpClientSample.java

/**
 * @param args the command line arguments
 *///from ww  w . j a va 2  s  . c om
public static void main(String[] args) throws IOException, JSONException {
    /** METHOD GET EXAMPLE **/
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://localhost:8000/test/api?id=100");
    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());
    }

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

    String output;
    System.out.println("Response:\n");

    while ((output = br.readLine()) != null) {
        JSONObject jsonObj = new JSONObject(output);
        System.out.println("json id : " + jsonObj.get("id"));
    }

    httpClient.getConnectionManager().shutdown();
}

From source file:com.mycompany.test.Jaroop.java

/**
 * This is the main program which will receive the request, calls required methods
 * and processes the response./* w  w  w .j  av a2s. c  om*/
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Scanner scannedInput = new Scanner(System.in);
    String in = "";
    if (args.length == 0) {
        System.out.println("Enter the query");
        in = scannedInput.nextLine();
    } else {
        in = args[0];
    }
    in = in.toLowerCase().replaceAll("\\s+", "_");
    int httpStatus = checkInvalidInput(in);
    if (httpStatus == 0) {
        System.out.print("Not found");
        System.exit(0);
    }
    String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles="
            + in;
    HttpURLConnection connection = getConnection(url);
    BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String request = "";
    StringBuilder response = new StringBuilder();
    while ((request = input.readLine()) != null) {
        //only appending what ever is required for JSON parsing and ignoring the rest
        response.append("{");
        //appending the key "extract" to the string so that the JSON parser can parse it's value,
        //also we don't need last 3 paranthesis in the response, excluding them as well.
        response.append(request.substring(request.indexOf("\"extract"), request.length() - 3));
    }
    parseJSON(response.toString());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {/*w  w  w .  j a v  a  2  s . com*/
        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(2)));
            while ((input = reader.readLine()) != null) {
                System.out.println(input);
            }
        }
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}