版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/athur666/article/details/78232555
什么是流
流是一组有序的,有起点和终点的字节集合,是对计算机中数据传输的总称或者抽象
即数据在两个设备间的传输称为流,流的本质是数据传输。
流序列中的数据可以是没有进行加工的原始数据(二进制字节数据),也可以是经过编码的符合某种格式规定的数据,Java中提供了不同的流类对它们进行处理。
流按照传输方向可以分为 按照传输方式可以分为
输入流 用于读取数据 含有Input 字节流 含有stream
输出流 用于写入数据 含有Output 字符流 不含stream
import java.io.*;
public class ExampleIo {
public static void main(String[] args)throws Exception {
new ExampleIo().bufferReaderWriter();
}
//字节流读取文件
public void zifuliuReader() throws Exception{
File ff=new File("E:\\today.txt");
FileInputStream in =new FileInputStream(ff);
int xx=0;
String value="";
while ((xx=in.read())!=-1){
System.out.print((char) xx);
value+=(char)xx;
}
in.close();
}
//字符流读取文件
public void zijieReader()throws Exception{
File ff=new File("E:\\today.txt");
int xx=0;
FileReader rd=new FileReader(ff);
while ((xx=rd.read())!=-1){
System.out.print((char)xx);
}
rd.close();
}
//字节流读取
byte[] ss= new String("goodluck").getBytes();
ByteArrayInputStream by= new ByteArrayInputStream(ss);
byte[] bs=new byte[1024];
int len=0;
while ((len=by.read(bs))!=-1){
System.out.println(new String(bs,0,len));
}
//字节流写入文件
public void zijieWriter()throws Exception{
File ff=new File("E:\\today.txt");
OutputStream out=new FileOutputStream(ff);
String zz="today is a good day";
byte[] b=zz.getBytes();
InputStream io2=new ByteArrayInputStream(b);
byte[] bs=new byte[1024];
int len=0;
while ((len=io2.read(bs))!=-1){
out.write(bs,0,len);
}
io2.close();
out.close();
}
//字符流写入文件
public void zifuWriter()throws Exception{
File ff=new File("E:\\today.txt");
FileWriter writer=new FileWriter(ff);
writer.write("今天是个好日子");
writer.close();
}
//字符流转换字节流的桥梁 可使用指定的 charset 将要写入流中的字符编码成字节。
public void TranferToZiJie()throws Exception{
File ff=new File("E:\\today.txt");
FileOutputStream out=new FileOutputStream(ff);
OutputStreamWriter writer=new OutputStreamWriter(out,"utf-8");
writer.write("今天是个好日子");
writer.close();
}
//将字节流向字符流的转换
public void TranferToZiFu()throws Exception{
File ff=new File("E:\\today.txt");
InputStreamReader in=new InputStreamReader(new FileInputStream(ff),"utf-8");
char[] b=new char[1024];
int s=in.read(b);
System.out.println(new String(b,0,s));
in.close();
}
//利用缓冲区读写文件
public void bufferReaderWriter()throws Exception{
File ff=new File("E:\\today.txt");
InputStreamReader in=new InputStreamReader(new FileInputStream(ff),"utf-8");
BufferedReader rd=new BufferedReader(in);
String value="";
while ((value=rd.readLine())!=null){
System.out.println(value);
}
rd.close();
OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream(ff),"utf-8");
BufferedWriter bf=new BufferedWriter(writer);
bf.write("今天是个好日子");
bf.close();
}
}