工具类关闭流及打印流
工具类关闭流(close)
package cn.Buffered; import java.io.Closeable; import java.io.IOException; public class FileUtil { /* * 工具类关闭流 * 可变参数:... 只能形参最后一个位置,处理方式与数组一致 * */ public static void close(Closeable ... io) { for(Closeable temp:io) { if(null!=temp) { try { temp.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /* * 使用泛型方法 */ public static <T extends Closeable> void closrAll(T ... io) { for(Closeable temp:io) { if(null!=temp) { try { temp.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
打印流(打印到文本,而不是控制台)
package cn.Buffered; import java.io.BufferedOutputStream; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; public class SystemDemo01 { public static void main(String[] args) throws FileNotFoundException { //重定向 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("C:/Users/Administrator/Desktop/sun/a.txt")),true)); System.out.println("a"); //控制台 --文件 System.out.println("sssa"); //返回控制台打印 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true)); System.out.println("sadafdfda"); } }
封装输入流(类似于Scanner)
package cn.Buffered; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Scanner { public static void main(String[] args) throws IOException { InputStream is= System.in; BufferedReader br=new BufferedReader(new InputStreamReader(is)); System.out.println("请输入"); String msg=br.readLine(); System.out.println(msg); } }