转换流:InputStreamReader、OutputStreamWriter
目的:把字节流转换为字符流
示例代码:
public class TestByte2CharStream {
private static File source;
private static File target;
static {
//io和bufferedstream这两个文件夹一定要存在
source = new File("io"+File.separator+"zhuanhuanstream"+File.separator+"source.txt");
target = new File("io"+File.separator+"zhuanhuanstream"+File.separator+"target.txt");
if(!source.exists()){
try {
source.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!target.exists()){
try {
target.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
testOutputStreamWriter();
testInputStreamReader();
}
public static void testInputStreamReader() throws IOException {
InputStream input = new FileInputStream(source);
InputStreamReader inputStreamReader = new InputStreamReader(input);
char[] data = new char[10];
int len;
while((len = inputStreamReader.read(data))!=-1){
System.out.println(new String(data,0,len));
}
inputStreamReader.close();
}
public static void testOutputStreamWriter() throws IOException {
OutputStream out = new FileOutputStream(source);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);
outputStreamWriter.write("我是传奇");
outputStreamWriter.close();
}
}