码迷,mamicode.com
首页 > 其他好文 > 详细

DataOutputStream和DataInputStream

时间:2018-05-01 10:48:16      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:名称   循环   exception   imp   org   tao   ice   文件的   bsp   

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[] names = {"衬衫", "手套", "围巾"};  // 商品名称
    float[] prices = {98.3f, 30.3f, 50.5f};  // 商品价格
    int[] nums = {3, 2, 1};  // 商品数量
    for (int i = 0; i < names.length; i++) {
      dos.writeChars(names[i]);  // 输出字符串
      dos.writeChar(‘\t‘);  // 输出分隔符
      dos.writeFloat(prices[i]);  // 输出价格
      dos.writeChar(‘\t‘);
      dos.writeInt(nums[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();
        }
      }
    }
  }

}

 

DataOutputStream和DataInputStream

标签:名称   循环   exception   imp   org   tao   ice   文件的   bsp   

原文地址:https://www.cnblogs.com/ss-123/p/8975443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!