【Java-----IO流(五)之数据流详解】

本文详细介绍了Java中的数据流概念及其分类,包括数据输出流DataOutputStream和数据输入流DataInputStream的使用方法,展示了如何通过这些流操作基本数据类型及字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据流概述

数据流也是处理流的一种,为了方便操作Java语言中的基本数据类型和String类型的数据,可以使用数据流来进行操作。数据流可以将我们Java语言中的基本数据类型和String类型的数据持久化存储到硬盘中,需要的时候就可以使用数据输入流将硬盘中持久存储的数据读入到程序中。这里的持久化存储和我们单独对文本的存储是不一样的,持久化存储到硬盘中的文件不是直接打开看的(打开看有的很多都会出现乱码),只是为了进行存储。

数据流分类

  • DataOutputStream:数据输出流,一般是套接在OutputStream类的子类对象上
  • DataInputStream:数据输入流,一般是套接在InputStream类的子类对象上

DataOutputStream

构造方法

public DataOutputStream(OutputStream out):创建一个新的数据输出流对象

FileOutputStream fos=new FileOutputStream("D:\\aaa\\helloworld.txt");
DataOutputStream dos=new DataOutputStream(fos);

常用方法

  • void writeBoolean()
dos.writeBoolean(true);
  • void writeByte()
byte b='?';
dos.writeByte(b);
  • void writeShort()
short s=12;
dos.writeShort(s);
  • void writeInt()
int i=3;
dos.writeInt(i);
  • void writeChar()
char c='a';
dos.writeChar(c);
  • void writeFloat()
float f=9;
dos.writeFloat(f);
  • void writeDouble()
double d=7.2;
dos.writeDouble(d);
  • void writeLong()
long l=10;
dos.writeLong(l);
  • void writeUTF():写字符串
  • void writeBytes(String s)
String str="中国";
dos.writeUTF(str);
dos.writeBytes(str);

DataInputStream

注意:我们使用数据输出流是按照什么顺序进行存储的,这个时候如果我们使用数据输入流读取时,也要按照相同的顺序读取

构造方法

public DataInputStream(InputStream in):创建一个新的数据输入流对象

FileInputStream fis=new FileInputStream("D:\\aaa\\helloworld.txt");
DataInputStream dis=new DataInputStream(fis);

常用方法

  • boolean readBoolean()
//dos.writeBoolean(true);
boolean boo=dis.readBoolean();
System.out.println(boo);
//输出:true
  • byte readByte()
/*
byte b='?';
dos.writeByte(b);
*/
byte by=dis.readByte();
System.out.println(by);
//输出:63
  • short readShort()
/*
short s=12;
dos.writeShort(s);
*/
short sh=dis.readShort();
System.out.println(sh);
//输出:12
  • int readInt()
/*
int i=3;
dos.writeInt(i);
*/
int in=dis.readInt();
System.out.println(in);
//输出:3
  • char readChar()
/*
char c='a';
dos.writeChar(c);
*/
char ch=dis.readChar();
System.out.println(ch);
//输出:a
  • float readFloat()
/*
float f=9;
dos.writeFloat(f);
*/
float fl=dis.readFloat();
System.out.println(fl);
//输出:9.0
  • double readDouble()
/*
double d=7.2;
dos.writeDouble(d);
*/
double db=dis.readDouble();
System.out.println(db);
//输出:7.2
  • long readLong()
/*
long l=10;
dos.writeLong(l);
*/
long lo=dis.readLong();
System.out.println(lo);
//输出:10
  • String readUTF():读取字符串
/*
String str="中国";
dos.writeUTF(str);
*/
String ss=dis.readUTF();
System.out.println(ss);
//输出:中国

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值