本文主要是介绍readLine()与read(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考:
readLine() 和 “\r”,“\n” 问题
被readLine()折腾了一把
httpURLConnection-网络请求的两种方式-get请求和post请求
关于BufferefReader.readLine()方法的理解
readLine()
功能:读取一个文本行。
一定要注意:
1、读入的数据要注意有/r或/n或/r/n
2、没有数据时会阻塞,在数据流异常或断开时才会返回null
3、使用socket之类的数据流时,要避免使用readLine(),以免为了等待一个换行/回车符而一直阻塞
4、readLine()是一个阻塞函数,当没有数据读取时,就一直会阻塞在那,而不是返回null
5、readLine()只有在数据流发生异常或者另一端被close()掉时,才会返回null值。
6、如果不指定buffer大小,则readLine()使用的buffer有8192个字符。在达到buffer大小之前,只有遇到"/r"、“/n”、“/r/n"才会返回。
7、该方法读取一行文本,当遇到换行符”\n",回车符"\r"或者回车符后面紧跟着换行符时,该行结束并返回。没有数据时,将会一直处于等待状态。因此在进行网络连接时,应该避免使用该方法。
read()
功能:读取单个字符的个数,如果已经读完的话会返回-1 (其范围从 0 到 65535 )
readLine()示例:
private static String getStringFromInputStream(InputStream a_is) {BufferedReader br = null;StringBuilder sb = new StringBuilder();String line;try {br = new BufferedReader(new InputStreamReader(a_is));while ((line = br.readLine()) != null) {//如果之前文件为空,则不执 行输出sb.append(line);}} catch (IOException e) {} finally {if (br != null) {try {br.close();} catch (IOException e) {}}}return sb.toString();}//b=bf.read())!=-1 每次都会先读取一个字符出来(不是字节)
//凡是inputstream和outputStream这种抽象类的子类。就是字节流。那么read()读的就是一个字节。
//Reader和Writer则是字符流。所以读的是一个字符
read()示例:
BufferedInputStream bis = null;ByteArrayOutputStream baos = new ByteArrayOutputStream();try {bis = new BufferedInputStream(getActivity().getAssets().open("movie" + position + ".txt"));byte[] bytes = new byte[1024];int i = -1;while ((i = bis.read(bytes)) != -1) {//单个读取计数,直到结束返回-1baos.write(bytes, 0, i);baos.flush();}String data = baos.toString();} catch (IOException e) {e.printStackTrace();} finally {try {bis.close();} catch (IOException e) {e.printStackTrace();}}
readLine测试:
/*** readLine函数会自动截取"\r","\n"之前的字符串*/public class ReaderTest {public static void main(String[] args) {try {String line = "helloworld";//readLine 读出后的长度: 10 readLine读的结果: helloworld
// String line = "hello\rworld";//readLine 读出后的长度: 5 readLine读的结果: hello
// String line = "\rworld";//readLine 读出后的长度: 0 readLine读的结果:OutputStream out = new FileOutputStream(".//out.txt");out.write(line.getBytes());InputStream in = new FileInputStream(".//out.txt");BufferedReader reader = new BufferedReader(new InputStreamReader(in));String str = reader.readLine();System.out.println("readLine 读出后的长度: " + str.length() + " readLine读的结果: " + str);} catch (IOException e) {e.printStackTrace();}}
}
read()测试
public class ReaderTestI {public static void main(String[] args) {try {
// String line = "helloworld";//helloworldString line = "hello\rworld";//world
// String line = "\rworld";//worldOutputStream out = new FileOutputStream(".//out.txt");out.write(line.getBytes());InputStream in = new FileInputStream(".//out.txt");byte[] b = new byte[50];in.read(b, 0, line.length());for (int i = 0; i < line.length(); i++) {System.out.print((char) b[i]);}} catch (IOException e) {e.printStackTrace();}}
}
这篇关于readLine()与read()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!