一、转换流
将字节流转换为字符流,来操作文本文档
转换流可以设定制定编码表
1、构造方法
(将字节输入流转为字符输入流)
(将字节输出流转为字符输出流)
(常用方法就是字符流的常用方法)
public class ReaderTest {
public static void main(String[] args) throws IOException{
InputStreamReader isr=new InputStreamReader(new FileInputStream("D:\\test\\c.txt"));
int read = isr.read();
System.out.println((char)read);
}
}
public class ReaderTest {
public static void main(String[] args) throws IOException{
OutputStreamWriter isw=new OutputStreamWriter(new FileOutputStream("D:\\test\\b.txt",true));
String s="hahahaha";
isw.write(s);
isw.close();
}
}
二、缓冲流
无论是字节流还是字符流都是一个一个进行读取操作,访问次数过多,对硬盘的磨损较大。
缓冲流自带缓冲区
字符流也有缓冲区,但它是进行字符转换的。
利用缓冲流进行数据读取示意图
字节输入缓冲流:BufferedInputStream
字节输出缓冲流:BufferedOutputStream
字符输入缓冲流:BufferedReader
字符输出缓冲流:BufferedWriter
1、缓冲字符输出流 BufferedWriter
构造方法
普通方法
public class BufferedTest {
public static void main(String[] args) throws IOException {
//定义一个字符串
String s="HAPPY EVERYDAY";
String s1="HAPPY";
//创建一个缓冲输出字符对象,参数为输出字符流
//缓冲流不能单独存在,必须有真正指向目标文件的流
BufferedWriter bWrite=new BufferedWriter(new FileWriter("D:\\test\\c.txt"));
//调用write()方法,将字符串写入
bWrite.write(s);
//使用newLine方法,进行换行
bWrite.newLine();
bWrite.write(s1);
//因为存在缓冲区,需进行刷新或者关闭流操作,才能将字符串写入文件中
bWrite.close();
}
}
2、缓冲字符输入流 BufferedReader
构造方法
常用方法
public class BufferedTest {
public static void main(String[] args) throws IOException {
//创建一个缓冲字符输入流对象,参数为具体指向的输入流对象
BufferedReader bReader=new BufferedReader(new FileReader("D:\\test\\c.txt"));
//调用readLine方法,读取一行数据
// String s = bReader.readLine();
// System.out.println(s);
String s;
//当数据读取完成时,返回值为null,使用null作为标志进行判断
while((s=bReader.readLine())!=null ){
System.out.println(s);
}
//关闭缓冲流
bReader.close();
}
}
3、缓冲字节输入流 BufferedInputStream
public class BufferedTest {
public static void main(String[] args) throws IOException {
//创建一个缓冲字节输入流,参数为具体的目标输入流对象
BufferedInputStream bi=new BufferedInputStream(new FileInputStream("D:\\test\\c.txt"));
//定义一个字节数组
byte[] bytes=new byte[1024];
int length;
//调用read方法读取字节数,返回字节数,若为空,返回-1
while((length=bi.read(bytes))!=-1){
System.out.println(new String(bytes,0,length));
}
//关闭流
bi.close();
}
}
4、缓冲字节输出流 BufferedOutputStream
注:在这里的字节流也需要进行刷新,才能成功写入文件
public class BufferedTest {
public static void main(String[] args) throws IOException {
//创建缓冲字符输出流对象
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\test\\d.txt"));
bos.write("abc".getBytes());
bos.write(System.lineSeparator().getBytes());
bos.write("www".getBytes());
//需要关闭流,才能将文件写入
bos.close();
}
}
来源:CSDN
作者:zj_2016
链接:https://blog.csdn.net/zj_2016/article/details/103218468