java 中 转换流是以字符流的形式操作字节流,需要注意一下两点:
1、操作内容必须是纯文本
2、指定字符集避免乱码
操作控制台输入输出:
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));) {
String msg = "";
while (!msg.equals("exit")) {
msg = br.readLine();
bw.write(msg);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
这里没有指定字符集是因为控制台和工程的字符集一致,不会乱码
操作网络流:
try (BufferedReader read = new BufferedReader(
new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8"));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("baidu.html"),"utf-8"));
) {
String msg = "";
while ((msg = read.readLine()) != null) {
System.out.println(msg);
writer.write(msg);
writer.newLine();
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
基本就这样的套路,一般为了提高性能都会套上BufferedRead 和 BufferredWrite。