字符流中的编码与解码,格式得一样,选用相同的编码和解码格式。
字符流写数据的5种方式:
void write(int c) :写入一个字符;
void write(char[] chars):写入一个字符数组
void write(char[] chars, int off, int len):写入字符数组的一部分
void write(String str) :写入一个字符串
选用相同的编码和解码格式:GBK,默认UTF-8;代码如下,
用void write(char[] chars, int off, int len)写入字符数组的一部分这种方式:
public class ConversionStreamDemo {
public static void main(String[] args) {
OutputStreamWriter osw = null;
InputStreamReader isr = null;
try {
//写入a.txt文件
osw = new OutputStreamWriter(new FileOutputStream("a.txt"),"GBK");
osw.write("唐人盛世一条街");
osw.flush();
//读取a.txt文件,并输出到控制台
isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK");
char[] chars = new char[1024];
int len = 0;
while ((len = isr.read(chars)) != -1){
System.out.println(new String(chars,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (osw != null && isr != null){
try {
osw.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}