Java連載156-IO總結(三)

一、管道流

  final PipedOutputStream pps = new PipedOutputStream();
  final PipedInputStream pis = new PipedInputStream(pps);
  new Thread(new Runnable() {
   public void run() {
    try {
     pps.write("厲害了".getBytes(StandardCharsets.UTF_8));
     pps.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }).start();
  
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     int b3 = 0;
     byte[] flush = new byte[1024];
     while ((b3=pis.read(flush)) != -1) {
      System.out.println(new String(flush, 0, flush.length));
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }).start();
  • 上面的管道流和Linux中的管道流是類似的

二、基本數據流

  • 可以使用DataInputStream等及逆行基本數據的存儲
  String address = "E:\\d05_gitcode\\Java\\newJava\\src\\com\\newJava\\newFile.txt";
  DataInputStream dis = new DataInputStream(new FileInputStream(address));
  byte b = dis.readByte();
  System.out.println(b);
  short s = dis.readShort();
  System.out.println(s);
  int i = dis.readInt();
  System.out.println(i);
  long l = dis.readLong();
  System.out.println(l);
  float f = dis.readFloat();
  System.out.println(f);
  double d = dis.readDouble();
  System.out.println(d);
  char c = dis.readChar();
  System.out.println(c);
  boolean bo = dis.readBoolean();
  System.out.println(bo);
  
  DataOutputStream dos = new DataOutputStream(new FileOutputStream(address));
  dos.writeByte(1);
  dos.writeShort(2);
  dos.writeInt(3);
  dos.writeLong(4L);
  dos.writeFloat(5.0f);
  dos.writeDouble(6.0d);
  dos.writeChar(7);
  dos.writeBoolean(false);
156.2
156.2

三、緩存流

  • CPU運行速度是內存的幾百倍,是磁盤的幾百萬倍,因此減少和磁盤的交互,就能提高IO的速度,我們在這兩者之間提供一個buffer,緩存流(也就是BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter), 來增多一次性讀寫的數量,減少IO的次數。 156.1

四、打印流

  • 我們所使用的System.out.println()方法就是打印流的一種
  StringWriter sw = new StringWriter();
  try (PrintWriter pw = new PrintWriter(sw)) {
   pw.println("lisudfos");
  }
  System.out.println("lisudfos");

五、源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章