下面列出了java.io.InputStreamReader#read ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
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();
}
}
/**
* 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();
}
}
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();
}
}
}
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);
}
}
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();
}
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*");
}
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();
}
}
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;
}
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);
}
}
}
@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();
}
}
}
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();
}
/**
* 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();
}
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--");
}
}
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();
}
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*");
}
/**
* 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);
}
}
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();
}
/**
* 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();
}
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);
}
}
}