吾知网

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 5578|回复: 0
打印 上一主题 下一主题

数据流对象DataInputStream、DataOutputStream的使用

[复制链接]
跳转到指定楼层
楼主
发表于 2015-11-21 17:16:07 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
数据流包括DataInputStream、DataOutputStream类,他们允许按照java的基础数据类型读写流中的数据。具体细节请查看java api;


public class DataOutputTest {

public static void main(String[] args) throws IOException {
  String username = "383065059";
  String path = "F:/workplaceT/Test/src/" + username;
  String inforTxt = "msg.db";
  File infoFile = new File(path + "/" + inforTxt);
  FileOutputStream fileOut = new FileOutputStream(infoFile);
  
  DataOutputStream out = new DataOutputStream(fileOut);
  //定义要保存的数据数组
  double[] prices={19.90,12.56,18.90,14.99,20.00};//长度5
  int[] amount={3,4,5,6,7,8};
  String[] descs={"java ee","java se","oracle","sqlserver","android"};
  //将prices,amount及descs中的数据以Tab键为分割保存到文件中。
  for(int i=0;i<5;i++){
   out.writeDouble(prices);
   out.writeChar('\t');
   
   out.writeInt(amount);
   out.writeChar('\t');
   
   out.writeUTF(descs);
   out.writeChar('\t');
  }
  out.close();
  
  //创建的数据输入流,将上面保存的文件再次打开并读取
  FileInputStream fileIn = new FileInputStream(infoFile);
  DataInputStream in=new DataInputStream(fileIn);
     double price;
     int amnt;
     String desc;
     double total=0.0;
     for(int i=0;i<5;i++){
      price=in.readDouble();
      in.readChar();//扔掉tab
      amnt=in.readInt();
      in.readChar();
      desc=in.readUTF();
      in.readChar();
      System.out.println("你订购了 "+amnt+"件 "+desc+",价格为 "+price);
      total=total+amnt*price;
     }
     System.out.println("共计金额:"+total+"元");
     in.close();
}

}

//读写为互逆操作,规律比较死。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|吾知网 ( 粤ICP备13013563号-1 )

GMT+8, 2024-5-18 03:15 , Processed in 1.101492 second(s), 10 queries , Memcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表