Java I/O系统
流模式
- 概念:
源和目标之间建立的通道。 流的分类
- 当源是程序的时候 → 输出流
输出流:字节输出流(OutputStream)、字符输出流(Writer)(一个字节等于两个字符)。 当目标为程序的时候 → 输入流
输入流:字节输入流(InputStream)、字符输入流(Reader)(一个字节等于两个字符)。
//选择流分类FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; //创建流对象 try { fileInputStream = new FileInputStream("E:/YM.jpg"); fileOutputStream = new FileOutputStream("D:/MY.jpg"); //操作流 int b = fileInputStream.read();//每 while((b=fileInputStream.read())!= -1){ fileOutputStream.write(b); } byte [] buffer = new byte [1024]; int length = 0; while ((length=fileInputStream.read(buffer))!= -1) { fileOutputStream.write(buffer, 0, length); fileOutputStream.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭流 if (fileInputStream != null) { try { fileInputStream.close(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fileOutputStream != null){ try { fileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- 当源是程序的时候 → 输出流
对象序列化与反序列化
要实现serializable接口(标记接口)- 序列化(Object InputStream)
概念:将对象以二进制流的形式输出 - 反序列化(Object OutputStream)
概念:将输入的二进制流转化为一个对象
- 序列化(Object InputStream)