输入字节流和字符流的使用原理
1:InputStream包含的三个方法:
1:int read() :从输入流中读取单个字节, int返回的是读取的字节个数;
2:int read(byte[]buff):从输入流中每一次读取的字节个数最大是buff.length()个; 并且读取的字节保存在数组buff里面; int 返回的是每次读取的字节个数的值;
3:int read(byte[]buff,int off,int len):从输入流中每一次读取的字节个数最大为len个字节数,并且存储在buff中不是从0开始 ,而是从off开始;
2:Reader包含的三个方法与InputStream包含的三个方法相同,只是保存的数组是字符数组 char[]cbuff;
InputStream demo1
import java.io.*;
/**
* FileInputStream的使用原理
* @author LiTing
*
*/
public class StreamDemo {
/**
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//FileInputStream继承 实现 InputStream
FileInputStream fis=new FileInputStream("f://aa.txt");
//定义一个保存读取一次的数据数组
byte[]buff=new byte[2];
int hasRead=0;
/**
* int fis.read(buff) 表示从输入流中每次读取最多的字节数是buff.length();
* 返回的int表示每次读取的字节个数
*
* 用while表示多次读取 ,因为当fis.read(buff)《0时,代表全部读取完毕,所以我们可以定义一个变量
* 保存每次读取的字节个数 -》hasRead
* 所以当hasRead《0时,读取完毕
*
* hasRead=2
*
*/
while((hasRead=fis.read(buff))>0)
{
// System.out.println(new String(buff,0,hasRead));
// System.out.println("hasRead="+hasRead);
/**
* hasRead=2
* nd
* hasRead=2
* js
* hasRead=2
* cd
*/
//String的一个方法 把一个字节数组转换成String类型
System.out.print(new String(buff,0,hasRead));
/**
* ndjscdn
* sdsd
*/
}
//关闭流
fis.close();
}
<strong><span style="color:#cc0000;">Reader demo1</span></strong><span style="font-size: 24px;">
</span><pre name="code" class="java" style="font-size: 24px;">/**
* FileReader的使用原理
* @author
*
*/
public class ReaderDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader fr=new FileReader("f://aa.txt");
//创建一个缓冲“竹筒”
char[]cbuff=new char[32];
//用来保存每一次读取的字符个数
int hasRead=0;
try {
while((hasRead=fr.read(cbuff))>0)
{
System.out.println("hasRead="+hasRead);
/**
* hasRead=13
* ndjscdn
* sdsd
*/
System.out.print(new String(cbuff,0,hasRead));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//在finally中关闭资源流
if(fr!=null)
fr.close();
}
}
}