976
外汇
Java中数据输入输出流——DataInputStream和DataOutputStream
一、基本概念
DataOutputStream
数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后应用程序可以使用数据输入流将数据读入。
DataOutputStream
数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。对于多线程访问不一定是安全的。 线程安全是可选的,它由此类方法的使用者负责。
二、例子
/**
* 必须先使用DataOutputStream写入数据,然后使用DataInputStream读取数据方可。
*
* @author 徐越
*
*/
public class TestClass
{
public static void main(String[] args) throws Exception
{
TestClass t = new TestClass();
t.write();
t.read();
}
public void write() throws Exception
{
String path = this.getClass().getClassLoader().getResource("test.txt").toURI().getPath();
OutputStream os = new FileOutputStream(path);
DataOutputStream dos = new DataOutputStream(os);
dos.writeDouble(Math.random());
dos.writeBoolean(true);
dos.writeInt(1000);
dos.writeInt(2000);
dos.flush();
os.close();
dos.close();
}
public void read() throws Exception
{
InputStream instream = this.getClass().getClassLoader().getResourceAsStream("test.txt");
DataInputStream dis = new DataInputStream(instream);
double d = dis.readDouble();
boolean b = dis.readBoolean();
// 先写的先被读出来
int i1 = dis.readInt();
int i2 = dis.readInt();
instream.close();
dis.close();
System.out.println(d);
System.out.println(b);
System.out.println(i1);
System.out.println(i2);
}
}
输出结果
0.4683893857027681
true
1000
2000
最后更新:2017-04-04 07:03:12
上一篇:
一个时代的命名
下一篇:
图的综合应用-迪杰斯特拉算法(导游图)
log4j的日志级别
什么是新零售?阿里巴巴最新的报告终于说清楚了!(附报告)
ASP.NET入门随想之抽象的力量
Oracle中计算日期之间相差的年月
WebSphere Application Server V7.0新特性及各Java EE标准版本支持之对比
纠结了好久才弄得明白一点点的汉诺塔问题,现在把一些方程与大家分享一下!
Ubuntu linux解决:”修改profile/enviroment文件无法进入ubuntu“的方法
缓存淘汰算法系列之3——FIFO类
ALICloudDB for PostgreSQL 试用报告 - 2 教你RDS PG的水平分库
Android 轻松实现语音识别