字节流和字符流的操用到的编码表和默认缓冲区大小。如果要自己指定这些值,需要构造两个方法。
想要实现字符流和字节流之间的相互转换需要用到两个类:
OutputStreamWriter 是字符流通向字节流的桥梁
InputStreamReader 是字节流通向字符流的桥梁
先看示例:
package com.zhaoqian.transstream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Demo1 {
public static void main(String[] args) throws IOException {
File f = new File("F:"+File.separator+"Demo"+File.separator+"test.txt");
// OutputStreamWriter 是字符流通向字节流的桥梁,创建了一个字符流通向字节流的对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
osw.write("我是字符流转换成字节流输出的");
osw.close();
}
}
字节流转换成字符流,编码格式为UTF-8
package com.zhaoqian.transstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo2 {
public static void main(String[] args) throws IOException {
File f = new File("F:"+File.separator+"Demo"+File.separator+"test.txt");
InputStreamReader inr = new InputStreamReader(new FileInputStream(f),"UTF-8");
char[] buf = new char[1024];
int len = inr.read(buf);
System.out.println(new String(buf,0,len));
inr.close();
}
}
获取键盘录入并存储
package com.zhaoqian.transstream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo3 {
// 键盘录入,存储在文件中
public static void main(String[] args) throws IOException {
// 将字节流转换成字符流,并使用字符缓冲区获取键盘录入
BufferedReader bur = new BufferedReader(new InputStreamReader(System.in));
// 目的文件
FileWriter fw = new FileWriter("F:\\Demo\\test.txt");
// 字符缓冲区,输出数据
BufferedWriter bw = new BufferedWriter(fw);
String line = null;
while((line=bur.readLine())!=null){
if ("over".equals(line)) {
break;
}
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
bur.close();
}
}