java中read()和readline()方法对比

来源:互联网 发布:网络订票在代办点取票 编辑:程序博客网 时间:2024/04/29 16:53

read方法:读取单个字符。 返回:作为一个整数(其范围从 0 到 65535 (0x00-0xffff))读入的字符,如果已到达流末尾,则返回 -1 ;

readLine方法:读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。 返回:包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null

 

example:

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class T0517 {

public static void main(String[] args) {

FileReader input;try {

input = new FileReader("c:/a.txt");

BufferedReader br = new BufferedReader(input);

for (int i = 0; i < 10; i++) {

System.out.println("read=" + br.read());

// System.out.println("readline=" + br.readLine());}

} catch (FileNotFoundException e) {e.printStackTrace();}

catch (IOException e) {e.printStackTrace();}}

}

=================================

C盘根目录下放入文件a.txt 里面内容有3行

a

1

123

===========

使用read测试(直接执行代码

)

==================

read=97

read=13

read=10

read=49

read=13

read=10

read=49

read=50

read=51

read=-1说明:返回的数字是字符的char型码,97=[a] ;49=[1];50=[2];51=[3];13=[回车];10=[换行];-1=[文件到底下面没有内容就返回-1总结:read返回文件中所有内容的char型码===========

使用readline测试(代码中注释掉那句,并把read注释掉执行)

===========

readline=a

readline=1

readline=123

readline=null

readline=null

readline=null

readline=null

readline=null

readline=null

readline=null

说明:很明显是取文件中每一行的内容输出最后,两个方法因为返回值不同,所以基本不会换着用,readline比较多用,因为方便,read用的相对少,因为要得到可读的内容,需要转码.

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击