学习目标:
提示:这里可以添加学习目标
例如:一周掌握 Java 入门知识
学习内容:
**以abc.txt为例**1、输入缓存流
File file = new File("D:\\IOtest\\test5\\abc.txt");
FileInputStream in = new FileInputStream(file);
BufferedInputStream inBuffer = new BufferedInputStream(in);
byte[] b = new byte[1024];
int temp;
String str="";
while((temp=inBuffer.read(b))!=-1)
{
str+= new String(b,0,temp);
}
2、输出缓存流
File file = new File("D:\\IOtest\\test5\\abc.txt");
FileOutputStream in = new FileOutputStream(file,true);
BufferedOutputStream out = new BufferedOutputStream(in);
out.write("是我".getBytes());
out.flush();
3、输入字节流
//指定文件
File file = new File("D:\\IOtest\\test5\\abc.txt");
//创建字符输入流对象
FileReader read = new FileReader(file);
char[] ch = new char[1024];
int sum;
String str = "";
while((sum = read.read(ch))!= -1)
{
str+= new String(ch,0,sum);
}
System.out.println(str);
4、输出字节流
//指定文件
File file = new File("D:\\IOtest\\test5\\abc.txt");
//创建字符输出流对象
FileWriter out = new FileWriter(file, true);
out.write("Lbj23");
out.flush();
5,输入字节缓冲流
File file = new File("D:\\IOtest\\test5\\abc.txt");
//创建字符输入流对象
FileReader fr = new FileReader(file);
//创建输入流缓冲
BufferedReader br = new BufferedReader(fr);
char[] ch = new char[1024];
int sum;
String str = "";
while((sum = br.read(ch))!= -1)
{
str+= new String(ch,0,sum);
}
System.out.println(str);
6,输出字节缓冲流
//指定文件
File file = new File("D:\\IOtest\\test5\\abc.txt");
//创建字节输出流对象
FileWriter fw = new FileWriter(file,true);
//创建输出流缓冲
BufferedWriter bw = new BufferedWriter(fw);
//输出字符串
bw.write("中华人民共和国万岁,中国人民万岁!!!");
//关闭资源
fw.flush();
bw.close();
7,字节—字符流
7.1字节输入流转字符流
File file = new File("D:\\IOtest\\lbj23.txt");
FileInputStream in = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(in);
7.2字节输出流转字符流
File file = new File("D:\\IOtest\\lbj23.txt");
FileOutputStream out = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(out);
ow.write("我爱你中国");
练习----------拷贝一份Txt文本使用字符输入输出缓冲流
一篇一万字的狗屁不通文章为例
public void copyTxt() throws Exception {
/*------------------------把文章读取出来------------------------------------*/
//指定文件
File file = new File("D:\\IOtest\\test5\\abc.txt");
//创建字符输入流对象
FileReader fr = new FileReader(file);
//创建输入缓冲流
BufferedReader br = new BufferedReader(fr);
char[] ch = new char[1024];
int sum;
String str = "";
while((sum = br.read(ch))!= -1)
{
str+= new String(ch,0,sum);
}
//关闭资源
fr.close();
br.close();
/*------------------------把文章写进去------------------------------------*/
//指定文件
File file2 = new File("D:\\IOtest\\lbj23.txt");
//创建字节输出流对象
FileWriter fw = new FileWriter(file2);
//创建输出流缓冲
BufferedWriter bw = new BufferedWriter(fw);
//把文章写进去
bw.write(str);
//关闭资源
fw.flush();
bw.flush();
}
学习时间:
2021/1/20
9:00~12:00