1、字節流與字符流之間的轉換,稱作轉換流
包括:InputStreamReader--->是字節流通向字符流的橋梁、OutputStreamWriter--->是字符流通向字節流的橋梁
~~~
import java.io.*;
import java.util.*;
import java.text.*;
public class TransStreamDemo{
public static void main(String []args)throws IOException{
//keyboardRW();
//fileprintToConsole();
//writeToFile();
//exceptionInfo();
printProperty();
}
//鍵盤讀寫方法
public static void keyboardRW()throws IOException{
//鍵盤錄入的最常見形式
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw =
new BufferedWriter(new OutputStreamWriter(System.out));
String line =null;
while((line = bufr.readLine())!=null){
bufw.write(line);
//換行
bufw.newLine();
//刷新緩沖
bufw.flush();
if("end".equals(line))
break;
}
bufr.close();
bufw.close();
}
//將文本文件打印到控制臺上
public static void fileprintToConsole()throws IOException{
BufferedReader bufr =
new BufferedReader(new InputStreamReader(new FileInputStream("TransStreamDemo.java")));
BufferedWriter bufw =
new BufferedWriter(new OutputStreamWriter(System.out));
String line =null;
while((line = bufr.readLine())!=null){
bufw.write(line.toUpperCase());
//換行
bufw.newLine();
//刷新緩沖
bufw.flush();
if("end".equals(line))
break;
}
bufr.close();
bufw.close();
}
//將鍵盤錄入的信息,寫到文件中
public static void writeToFile()throws IOException{
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("sys.txt")));
String line =null;
while((line = bufr.readLine())!=null){
bufw.write(line);
//換行
bufw.newLine();
//刷新緩沖
bufw.flush();
if("end".equals(line))
break;
}
bufr.close();
bufw.close();
}
/**
掌握什么時候使用哪種類型的流
要做到3個明確
1、明確源和目的
源包括:內存、硬盤、鍵盤。使用InputStream Reader
目的包括:內存、硬盤、控制臺。使用OutputStream Writer
若操作的是文本對象,那么選擇Reader
若是圖片、mp3等資源文件,使用Stream對象
2、明確操作的設備:內存、硬盤、控制臺。確定使用哪個對象
3、。。。。。。
*/
//打印異常日志信息
public static void exceptionInfo(){
try{
int[] arr = new int[]{0,2,1};
System.out.println(arr[3]);
}catch(Exception e){
PrintStream ps = null;
try{
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒");
String s = sdf.format(d);
//重寫printStackTrace(PrintStream s) 方法
ps =new PrintStream("exception.log");
ps.print(s);
System.setOut(ps);
}catch(Exception ex){
throw new RuntimeException("日志錄入出錯");
}
e.printStackTrace(System.out);
}
}
//打印系統信息
public static void printProperty()throws IOException{
Properties p = System.getProperties();
PrintStream ps = new PrintStream("properties.txt");
//該方法是設置流到指定的目的中去
System.setOut(ps);
//設置打印對象
p.list(System.out);
}
}
~~~