IO的体系。所具备的的两个基本功能就是:读和写
1、字节流
InputStream(读), OutputStream(写)
2、字符流
Reader(读), Writer(写)
程序一:将文本数据存储到文件中
//将文本读取到文件
public static void writerFile(){
FileWriter fw = null;
try{
fw = new FileWriter("demo.txt");
fw.write("abcdec");
fw.flush();
fw.write("kkkk");
}catch(Exception e){
e.printStackTrace();
}finally{
if(fw != null){
try{
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
另外一个小细节:
当指定绝对路径时,定义目录分隔符有两种方式:
1、反斜线 但是一定要写两个。\\ new FileWriter("c:\\demo.txt");
2、线性 / 写一个即可。 new FileWriter("c:/demo.txt");
程序二:读取一个已有的文本文件,每次读取一个字符
//将已有的文件中的文本打印出来
public static void readFile(){
FileReader fr = null;
try{
int ch = 0;
fr = new FileReader("demo.txt");
//一次读取一个字符
while((ch = fr.read())!=-1){
System.out.println((char)ch);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(fr != null){
try{
fr.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
字符流的缓冲区
缓冲区的出现提高了对流的操作效率
对应的对象:
BufferedWriter:
特有的方法:newLine():跨平台的换行符
BufferedReader:
特有的方法:readLine():一次读一行,到行标记时,将行标记之前的字符数据作为字符串返回,读到末尾时,返回null
程序三:通过缓冲对文件进行复制
//通过缓冲实现对文件的复制
public static void copyFile(){
BufferedReader br = null;
BufferedWriter bw = null;
try{
br = new BufferedReader(new FileReader("demo.txt"));
bw = new BufferedWriter(new FileWriter("demo2.txt"));
String line = null;
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(br != null){
try{
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(bw != null){
try{
bw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
字节流
抽象基类:InputStream, OutputStream
字节流可以操作任何数据
注意:字符流使用的数组是字符数组:char[] chs
字节流使用的数组是字节数组:byte[] bt
转换流:
特点:1、是字节流和字符流之间的桥梁
2、该对象中可以对读取的字节数据进行指定编码表的编码转换
具体的对象体现:
1、InputStreamReader:字节到字符的桥梁
2、OutputStreamWriter:字符到字节的桥梁
这两个流对象是字符流体系中的成员
所以他们要实现转换作用,而本身又是字符流。所以在构造的时候,需要传入字节流对象进来
对象序列化
ObjectInputStream
ObjectOutputStream
可以通过这两个对象直接操作已有对象并将对象进行本地持久化存储