java.io包中包括字节流和字符流两大类,每类都有输入和输出操作。
区别:字节流操作是不带缓冲的的,即不会使用到缓冲区,是对文件进行直接操作的,而字符流操作使用缓冲区,通过缓冲区再对文件进行操作。关闭字符流操作时会将缓冲区的内容写到文件中去。特此说明:如果以下两个实例都不关闭流,则字节流操作后文件内有内容,而字符流操作后文件内容并没有改变(指没有追加进去),体现了字符流与字节流在缓冲上的区别。当然也可以使用flush函数强行进行缓存区冲洗。
(1)字节流
字节流中输出和输入数据使用OutPutStream和InPutStream类
OutPutStream和InPutStream是抽象类,实例化必须通过其子类进行,操作文件时分别使用FileOutputStream和FileInputStream
实例代码:
import java.io.*;
public class Demo07 {
public static void main (String[] args) throws Exception{
// TODO Auto-generated method stub
/*File 类实例化*/
File file=new File("test.txt");
/*OutputStream实例化通过FileOutputStream进行*/
OutputStream out=new FileOutputStream(file);
/*写入文件的数据*/
String str="If winter comes , can spring be far behind?";
/*将字符串转换成字节流*/
byte bOut[]=str.getBytes();
/*按字节流写入文件*/
out.write(bOut);
out.close(); //关闭文件
/*InputStream实例化通过FileInputStream进行*/
InputStream in=new FileInputStream(file);
/*数据缓存*/
byte bIn[]=new byte[1024];
/*从文件中按字节流读取数据*/
int len=in.read(bIn);
/*将字节流装换为字符串输出*/
System.out.println(new String(bIn,0,len));
in.close(); //关闭文件
}
}
运行结果:
(2)字符流
字节流中输出和输入数据使用Writer和Reader类,
Writer和Reader类是抽象类,实例化必须通过其子类进行,操作文件时分别使用FileWriter和FileReader
实例代码:
import java.io.*;
public class Demo07 {
public static void main (String[] args) throws Exception{
// TODO Auto-generated method stub
/*File 类实例化*/
File file=new File("test.txt");
/*Writer实例化通过FileWriter进行,操作文件此处为追加方式*/
Writer out=new FileWriter(file,true);
/*写入文件的数据*/
String str="\t\nIf winter comes , can spring be far behind?";
/*按字符流写入文件*/
out.write(str);
out.close(); //关闭文件
/*Reader实例化通过FileReader进行*/
Reader in=new FileReader(file);
/*数据缓存,为字符流*/
char bIn[]=new char[1024];
/*从文件中按字符流读取数据*/
int len=in.read(bIn);
/*将字符流装换为字符串输出*/
System.out.println(new String(bIn,0,len));
in.close(); //关闭文件
}
}
运行结果: