【基础篇】java中输入输出的总括——数据流

本文通过实例演示了Java中DataInputStream和DataOutputStream的使用方法,包括如何将基本数据类型如int、String等写入文件及从文件中读取这些数据。

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

不想把别人的东西占为己有,但是想方便日后参考还是摘录了。

烦死了,看Java编程思想三或者四,感觉老外写书跟我们看书的习惯都不一样的,总感觉老外写的东西就像是在写手册,全面但是烦琐。

【原则】不要告诉我历史,告诉我怎么做就行了。

【事实】输出输入类,就是TMD的简单,为什么非要弄成手册,让我这个菜鸟看不懂

【鸣谢】中国IT实验室的总结篇

 ——————————————————————————————————————————————————————————

数据流


DataInputStream和DataOutputStream
     在提供了字节流的读写手段的同时,
     以统一的通用的形式向输入流中写入boolean,int,long,double等基本数据类型,并可以在次把基本数据类型的值读取回来。
     提供了字符串读写的手段。
     分别实现了DataInput和DataOutput接口
声明类:
Public class DataInputStream extends filterInputStream implements DataInput
例 8.9 数据流。
本例演示数据流的使用方法。
程序如下:
import java.io.*;
public class Datastream
{
public static void main(String arg[])
{
String fname = "student1.dat";
new Student1("Wang").save(fname);
new Student1("Li").save(fname);
Student1.display(fname);
}
}
class Student1
{
static int count=0;
int number=1;
String name;
Student1(String n1)
{
this.count++; //编号自动加1
this.number = this.count;
this.name = n1;
}
Student1()
{
this("");
}
void save(String fname)
{
try
{ //添加方式创建文件输出流
FileOutputStream fout = new FileOutputStream(fname,true);
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(this.number);
dout.writeChars(this.name+"/n");
dout.close();
}
catch (IOException ioe){}
}
static void display(String fname)
{
try
{
FileInputStream fin = new FileInputStream(fname);
DataInputStream din = new DataInputStream(fin);
int i = din.readInt();
while (i!=-1) //输入流未结束时
{
System.out.print(i+" ");
char ch ;
while ((ch=din.readChar())!='/n') //字符串未结束时
System.out.print(ch);
System.out.println();
i = din.readInt();
}
din.close();
}
catch (IOException ioe){}
}
}
程序运行结果如下:
1 Wang
2 Li

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值