Java Code Examples for java.io.InputStreamReader#read()

The following examples show how to use java.io.InputStreamReader#read() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 *  Reads a single line of input from the console.
 *
 *  @param console input
 *  @param echo whether the input should be echoed (e.g. false for passwords, other sensitive data)
 */
private String read(InputStreamReader console, boolean echo) {
	StringBuilder builder = new StringBuilder();
	try {
		for (char c = (char) console.read(); !(c == '\n' || c == '\r'); c = (char) console.read()) {
			if (echo) {
				System.out.print(c);
			}
			builder.append(c);
		}
		System.out.println();
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
	return builder.toString();
}
 
Example 2
Source Project: Xndroid   File: ShellUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void checkRoot() {
    sRoot = false;
    char[] buff = new char[1024];
    try {
        Process process = Runtime.getRuntime().exec("su");
        OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
        InputStreamReader input = new InputStreamReader(process.getInputStream());
        String testStr = "ROOT_TEST";
        output.write("echo " + testStr + "\n");
        output.flush();
        output.write("exit\n");
        output.flush();
        process.waitFor();
        int count = input.read(buff);
        if (count > 0) {
            if (new String(buff, 0, count).startsWith(testStr))
                sRoot = true;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 3
Source Project: box-java-sdk   File: BoxJSONResponse.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the body of the response as a JSON string. When this method is called, the response's body will be read and
 * the response will be disconnected, meaning that the stream returned by {@link #getBody} can no longer be used.
 * @return the body of the response as a JSON string.
 */
public String getJSON() {
    if (this.jsonObject != null) {
        return this.jsonObject.toString();
    } else {
        InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8);
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[BUFFER_SIZE];

        try {
            int read = reader.read(buffer, 0, BUFFER_SIZE);
            while (read != -1) {
                builder.append(buffer, 0, read);
                read = reader.read(buffer, 0, BUFFER_SIZE);
            }

            this.disconnect();
            reader.close();
        } catch (IOException e) {
            throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
        }
        this.jsonObject = JsonObject.readFrom(builder.toString());
        return builder.toString();
    }
}
 
Example 4
Source Project: anthelion   File: TestSWFParser.java    License: Apache License 2.0 6 votes vote down vote up
public TestSWFParser(String name) { 
  super(name);
  for (int i = 0; i < sampleFiles.length; i++) {
  try {
    // read the test string
    FileInputStream fis = new FileInputStream(sampleDir + fileSeparator + sampleTexts[i]);
    StringBuffer sb = new StringBuffer();
    int len = 0;
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    char[] buf = new char[1024];
    while ((len = isr.read(buf)) > 0) {
      sb.append(buf, 0, len);
    }
    isr.close();
    sampleTexts[i] = sb.toString().replaceAll("[ \t\r\n]+", " ").trim();
  } catch (Exception e) {
    e.printStackTrace();
  }
  }
}
 
Example 5
public static String read(String host, int port, String dataToSend) {
    try {
        Socket socket = new Socket(host, port);
        InputStreamReader reader = new InputStreamReader(socket.getInputStream());
        if (dataToSend != null) {
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
            outputStream.writeBytes(dataToSend);
        }
        StringBuilder content = new StringBuilder();
        int c = reader.read();
        while (c != -1) {
            content.append((char)c);
            c = reader.read();
        }
        reader.close();
        return content.toString();
    }
    catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 6
Source Project: ant-ivy   File: VsftpRepository.java    License: Apache License 2.0 6 votes vote down vote up
private void exec(String command) throws IOException {
    Message.debug("launching '" + command + "'");
    process = Runtime.getRuntime().exec(command);
    in = new InputStreamReader(process.getInputStream());
    err = new InputStreamReader(process.getErrorStream());
    out = new PrintWriter(process.getOutputStream());

    errorsReader = new IvyThread() {
        public void run() {
            initContext();
            int c;
            try {
                // CheckStyle:InnerAssignment OFF
                while (err != null && (c = err.read()) != -1) {
                    errors.append((char) c);
                    errorsLastUpdateTime = System.currentTimeMillis();
                }
                // CheckStyle:InnerAssignment ON
            } catch (IOException e) {
                // nothing to do
            }
        }
    };
    errorsReader.start();
}
 
Example 7
private String[] parseMigrationFile(InputStreamReader migrationInput) throws IOException {
    StringBuilder sb = new StringBuilder();
    char[] buf = new char[4096];

    int len;
    while ((len = migrationInput.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString().replace("\n", " ").split(";\\s*");
}
 
Example 8
Source Project: javalite   File: RuntimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    try {
        InputStreamReader reader = new InputStreamReader(is);
        int s;
        while ((s = reader.read()) != -1) {
            if(buffer.size() == maxBuffer){
                buffer.remove(0);
            }
            buffer.add((char)s); // boxing
        }
        is.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 9
Source Project: kcanotify   File: Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static StringBuilder readString(InputStreamReader reader) {
    StringBuilder sb = new StringBuilder(2048);
    char[] read = new char[128];
    try {
        for (int i; (i = reader.read(read)) >= 0; sb.append(read, 0, i)) ;
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
    return sb;
}
 
Example 10
Source Project: flow   File: DevModeHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void readLinesLoop(Pattern success, Pattern failure,
        InputStreamReader reader) throws IOException {
    StringBuilder line = new StringBuilder();
    for (int i; (i = reader.read()) >= 0;) {
        char ch = (char) i;
        console("%c", ch);
        line.append(ch);
        if (ch == '\n') {
            processLine(line.toString(), success, failure);
            line.setLength(0);
        }
    }
}
 
Example 11
Source Project: Elasticsearch   File: LocalRestChannel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doSendResponse(RestResponse response) {
    status = response.status().getStatus();

    byte[] bytes = response.content().toBytes();
    long length = bytes.length;
    Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
    if(length < 0) {
        length = 4096;
    }

    InputStream instream =  new ByteArrayInputStream(bytes);
    InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
    CharArrayBuffer buffer = new CharArrayBuffer((int)length);
    char[] tmp = new char[1024];

    int l;
    try {
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        content = buffer.toString();
    } catch (IOException e) {
        status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
        content = "IOException: " + e.getMessage();
    } finally {
        try {
            reader.close();
            instream.close();
        } catch (IOException e1) {
            content = "IOException: " + e1.getMessage();
        } finally {
            count.countDown();
        }
    }
}
 
Example 12
Source Project: jdit   File: DataMigration.java    License: MIT License 5 votes vote down vote up
private static String readStream(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder(BUFFER_SIZE);
    InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
    char[] buffer = new char[BUFFER_SIZE];
    int readBytes;
    while ((readBytes = reader.read(buffer)) > -1) {
        sb.append(buffer, 0, readBytes);
    }
    return sb.toString();
}
 
Example 13
/**
 * Copy the contents of the given InputStream into a String.
 * Leaves the stream open when done.
 * @param in the InputStream to copy from
 * @param charset charset
 * @return the String that has been copied to
 * @throws IOException in case of I/O errors
 */
public static String copyToString(InputStream in, Charset charset) throws IOException {
	StringBuilder out = new StringBuilder();
	InputStreamReader reader = new InputStreamReader(in, charset);
	char[] buffer = new char[BUFFER_SIZE];
	int bytesRead = -1;
	while ((bytesRead = reader.read(buffer)) != -1) {
		out.append(buffer, 0, bytesRead);
	}
	return out.toString();
}
 
Example 14
Source Project: stynico   File: htmlActivity.java    License: MIT License 5 votes vote down vote up
private void urlConGetWebData() throws IOException
   {

String pediyUrl=ped.getText().toString();


URL url = new URL(pediyUrl);
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{		
    //Log.d("TAG", "---into-----urlConnection---success--");

    InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
    int i;
    String content = "";
    while ((i = isr.read()) != -1)
    {
	content = content + (char)i;
    }
    mHandler.obtainMessage(MSG_SUCCESS, content).sendToTarget();
    isr.close();
    httpConn.disconnect();
}
else
{
    //Log.d("TAG", "---into-----urlConnection---fail--");

}

   }
 
Example 15
public static String readAsString(InputStream inputStream) throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    char[] buffer = new char[4096];
    int length;
    while ((length = reader.read(buffer)) != -1) {
        builder.append(buffer, 0, length);
    }
    return builder.toString();
}
 
Example 16
private String[] parseMigrationFile(InputStreamReader migrationInput) throws IOException {
    StringBuilder sb = new StringBuilder();
    char[] buf = new char[4096];

    int len;
    while ((len = migrationInput.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString().replace("\n", " ").split(";\\s*");
}
 
Example 17
/**
 * Main to run from tests from command line.
 * @param args ignored.
 */
public static void main(final String[] args) throws IOException {
    final InputStreamReader input = new InputStreamReader(System.in);
    int c;
    while ((c = input.read()) != -1) {
      if (c >= 'A' && c <= 'M' || c >= 'a' && c <= 'm') {
        c += 'N' - 'A';
      } else if (c >= 'N' && c <= 'Z' || c >= 'n' && c <= 'z') {
        c -= 'N' - 'A';
      }
      System.out.print((char) c);
    }
  }
 
Example 18
Source Project: netbeans   File: RunTCK.java    License: Apache License 2.0 5 votes vote down vote up
private String readUrl() throws IOException {
    InputStreamReader r = new InputStreamReader(test.openStream());
    StringBuilder sb = new StringBuilder();
    for (;;) {
        int ch = r.read();
        if (ch == -1) {
            break;
        }
        sb.append((char)ch);
    }
    return sb.toString();
}
 
Example 19
/**
 * Insert an XML document into the received column of the received
 * test table using setString.  This method parallels "insertFiles"
 * above, except that it should be used for documents that require
 * a Document Type Definition (DTD).  In that case the location of
 * the DTD has to be modified _within_ the document so that it can
 * be found in the running user directory.
 *
 * Expectation is that the file to be inserted is in the directory
 * indicated by HELPER_FILE_LOCATION and that the DTD file has been
 * copied to the user's running directory (via use of the util
 * methods in SupportFilesSetup).
 *
 * @param conn Connection on which to perform the insert.
 * @param tableName Table into which we want to insert.
 * @param colName Column in tableName into which we want to insert.
 * @param fName Name of the file whose content we want to insert.
 * @param dtdName Name of the DTD file that the received file uses.
 * @param numRows Number of times we should insert the received
 *  file's content.
 */
public static void insertDocWithDTD(Connection conn, String tableName,
    String colName, String fName, String dtdName, int numRows)
    throws IOException, SQLException, PrivilegedActionException
{
    // Read the file into memory so we can update it.
    fName = HELPER_FILE_LOCATION + fName;
    java.net.URL xFile = BaseTestCase.getTestResource(fName);
    Assert.assertNotNull("XML input file missing: " + fName, xFile);

    int charCount = 0;
    char [] cA = new char[1024];
    StringBuilder sBuf = new StringBuilder();
    InputStreamReader reader =
        new InputStreamReader(BaseTestCase.openTestResource(xFile));

    for (int len = reader.read(cA, 0, cA.length); len != -1;
        charCount += len, len = reader.read(cA, 0, cA.length))
    {
        sBuf.append(cA, 0, len);
    }

    reader.close();

    // Now replace the DTD location.

    java.net.URL dtdURL = SupportFilesSetup.getReadOnlyURL(dtdName);
    Assert.assertNotNull("DTD file missing: " + dtdName, dtdURL);

    String docAsString = sBuf.toString();
    int pos = docAsString.indexOf(dtdName);
    if (pos != -1)
        sBuf.replace(pos, pos+dtdName.length(), dtdURL.toExternalForm());

    // Now (finally) do the insert using the in-memory document with
    // the correct DTD location.
    docAsString = sBuf.toString();
    PreparedStatement pSt = conn.prepareStatement(
        "insert into " + tableName + "(" + colName + ") values " +
        "(xmlparse(document cast (? as clob) preserve whitespace))");

    for (int i = 0; i < numRows; i++)
    {
        pSt.setString(1, docAsString);
        pSt.execute();
    }

    pSt.close();
}
 
Example 20
public int decode(final InputStream in, final Appendable sb) {

        final ByteCountInputStream bcis = new ByteCountInputStream(in);
        
        // Wrap with decoder
        final InputStreamReader r = new InputStreamReader(bcis, cs);

        try {

            // decode
            int ch;
            while ((ch = r.read()) != -1) {

                sb.append((char) ch);

            }

            return bcis.getNRead();
            
        } catch (IOException ex) {

            throw new RuntimeException(ex);

        } finally {

            try {
                r.close();
            } catch (IOException e) {
                log.error(e, e);
            }

        }

    }