重定向IO
引用自:http://www.cnblogs.com/liunanjava/p/4307793.html
?
1.三個靜態變量
java.lang.System提供了三個靜態變量
- System.in(默認鍵盤)
- System.out(默認顯示器)
- System.err
- System提供了三個重定向方法
2.重寫向方法
System提供了三個重定向方法
| 方法 | 說明 |
| static void setErr(PrintStream errr) | 重定向標準錯誤輸出流 |
| static void setIn(InputStream in ) | 重定向標準輸入流 |
| static void setOut(PrintStream out) | 重定向歀輸出流 |
3.實例
重定向輸入流
?
package com.pb.io.reio;import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;/** 重定向輸入* 1.有一個已經初始化的InputStream輸入流* 2.調用System.setIn()方法,將標淮輸入流重定向到目的輸入流* 3.讀取System.in中的內容*/ public class ReIn {public static void main(String[] args) throws UnsupportedEncodingException{ try {//1.聲明一個輸入流FileInputStream fis=new FileInputStream("d:/test/s1.txt");//2.重定向 System.setIn(fis);//3.讀取System.in標準輸入流中的內容BufferedReader br=new BufferedReader(new InputStreamReader(System.in,"gb2312")); //設置字符編碼//4.輸出System.in中的內容String line=null;while((line=br.readLine())!=null){System.out.println(line);}//5.關閉流 br.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }
?
重定向輸出流
package com.pb.io.reio;import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream;/** 重定向標淮輸出流* 1.初始化PrintStream對象* 2.調用System.setOut()方法,將標淮輸出流重定向至PrintStream對象* 3.操作System.out流,*/ public class ReOut {public static void main(String[] args) {try {//1.聲明一個輸出流PrintStream對象PrintStream ps=new PrintStream(new FileOutputStream("d:/test/ps.txt",true)); //追加內容//2.重定向標淮輸出流 System.setOut(ps);//3.使用PrintStream對象向流中寫信息System.out.println("測試重定向成功了沒有!");System.out.println(new ReOut());ps.close();} catch (FileNotFoundException e) {e.printStackTrace();} } }?
轉載于:https://www.cnblogs.com/Tinyshine/p/4774193.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: idea中导包的快捷键
- 下一篇: IT职场的一些处事之道