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

The following examples show how to use java.io.InputStreamReader#read() . 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
Source File: ConsoleUserInput.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
/**
 *  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 File: VsftpRepository.java    From ant-ivy with 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 3
Source File: SocketTestUtils.java    From reactive-ipc-jvm with Apache License 2.0 6 votes vote down vote up
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 4
Source File: TestSWFParser.java    From anthelion with 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
Source File: BoxJSONResponse.java    From box-java-sdk with 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 6
Source File: ShellUtils.java    From Xndroid with 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 7
Source File: DevModeHandler.java    From flow with 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 8
Source File: LocalRestChannel.java    From Elasticsearch with 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 9
Source File: DataMigration.java    From jdit with 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 10
Source File: StreamUtils.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: htmlActivity.java    From stynico with 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 12
Source File: IoUtils.java    From Sword_emulator with GNU General Public License v3.0 5 votes vote down vote up
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 13
Source File: Util.java    From kcanotify with 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 14
Source File: RuntimeUtil.java    From javalite with 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 15
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 16
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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
Source File: SpawnJvmTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 File: RunTCK.java    From netbeans with 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
Source File: XML.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 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
Source File: BOCU1Compressor.java    From database with GNU General Public License v2.0 3 votes vote down vote up
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);
            }

        }

    }