read()把字节读取成字符,按字符进行读取输出流,
readline()按行读取,直到读到空格或者换行符停止。
这俩可以互换使用,readline速度略慢,:
//按字符读取
Runtime run = Runtime.getRuntime ();
Process process = run.exec ( cmd );
InputStream in = process.getInputStream ();
StringBuffer out = new StringBuffer ();
byte[] b = new byte[8192];
for (int n; (n = in.read ( b )) != -1; ) {
out.append ( new String ( b, 0, n ) );
}
System.out.println ( out.toString () );
in.close ();
process.destroy ();
-----------------------------------------------------------------------------------------------------------------------------
//按行读取
String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "application/vnd.edusoho.v2+json");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
本文比较了Java中`read()`和`readline()`方法在处理输入流时的效率和用法,展示了如何通过这两个函数实现字符逐个读取和按行获取,特别突出了`readline()`的特性。
1259

被折叠的 条评论
为什么被折叠?



