转换流类别:
OutputStreamWriter:是Writer的子类,将输出的字符流变成字节流,即将一个字符流的输出对象变成字节流输出对象。
InputStreamReader:是Reader的子类,将输入的字节流变成字符流,即将一个字节流的输入对象变成字符流的输入对象
以文件操作为例:内存中的字符数据需要通过OutputStreamWrite变为字节流才能保存在文件中。读取时需要将读入的字节流通过InputStreamReader变为字符流。
一、将字符输出流变为字节输出流
public class OutputStreamWriterDemo {
public static void main(String[] args) {
File f = new File("D:"+File.separator+"test.txt");
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(f));
writer.write("将字符输出流变成字节输出流");
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、将字符输入流变成字节输入流:
public class InputStreamReaderDemo {
public static void main(String[] args) {
File f = new File("D:"+File.separator+"test.txt");
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(f));
char c[] = new char[1024];
int len = reader.read(c);
reader.close();
System.out.println("读取:"+new String(c,0,len));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}