DataOutputStream and DataInputStream

时间:2022-09-05 09:34:08

1、在io包中,提供了两个与平台无关的数据操作流

  数据输出流(DataOutputStream)

  数据输入流(DataInputStream)

2、通常数据输出流会按照一定的格式将数据输出,再通过数据输入流按照一定的格式将数据读入

-------------------------------------------------------------------------------------

(1)DataOutputStream

package org.example.io;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestDataOutputStream {

  public static void main(String[] args) throws IOException {
    DataOutputStream dos = null;
    File f = new File("e:\\s\\test\\a.txt");
    dos = new DataOutputStream(new FileOutputStream(f));
    String[] name = {"衬衫", "手套", "围巾"};
    float[] price = {98.3f, 30.3f, 50.5f};
    int[] num = {3, 2, 1};
    for (int i = 0; i < name.length; i++) {
      dos.writeChars(name[i]);
      dos.writeChar('\t');
      dos.writeFloat(price[i]);
      dos.writeChar('\t');
      dos.writeInt(num[i]);
      dos.writeChar('\n');
    }
    dos.flush();
    dos.close();
  }

}

-------------------------------------------------------------------------------------

(2)DataInputStream

package org.example.io;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestDataInputStream {

  public static void main(String[] args) {

    DataInputStream dis = null;
    File f = new File("e:\\s\\test\\a.txt");
    try {
      dis = new DataInputStream(new FileInputStream(f));
      String name = null;
      float price = 0.0f;
      int num = 0;
      char[] temp = null;  /* 接收商品名称 */
      int len = 0;  /* 保存读取数据的个数 */
      char c = 0;  /* '\u0000' */
      while (true) {
        temp = new char[200];
        len = 0;
        while ((c = dis.readChar()) != '\t') {  /* 单个字符地循环读取商品名称 */
          temp[len] = c;
          len++;
        }
        name = new String(temp, 0, len);  /* 商品名称 */
        price = dis.readFloat();  /* 读取价格 */
        dis.readChar();  /* 读取\t */
        num = dis.readInt();  /* 读取数量 */
        dis.readChar();  /* 读取\n */
        System.out.println("Name:"+name+"\t\tPrice:"+price+"\tNum:"+num);
      }
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (dis != null) {
        try {
          dis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

}