阅读251 返回首页    go 阿里云 go 技术社区[云栖]


Java IO--数据操作流DataOutputStream/DataInputStream

数据操作流:

与平台无关的数据操作流:DataOutputStream、DataInputStream

如果要想使用数据操作流,则肯定要由用户自己指定数据的保存格式,必须按指定好的格式保存数据,才可以使用数据输入流将数据读取进来。

DataOutputStream:


DataOutput接口定义了一系列的writeXxx()的操作,可以写入各种数据类型的数据。
要想使用DataOutputStream写入数据的话,则必须指定好数据的输出格式。

每一行的数据,通过“\n”完结,每行中的各个数据之间通过“\t”完结。
import java.io.DataOutputStream ;
import java.io.File ;
import java.io.FileOutputStream ;
public class DataOutputStreamDemo{
	public static void main(String args[]) throws Exception{	// 所有异常抛出
		DataOutputStream dos = null ;			// 声明数据输出流对象
		File f = new File("d:" + File.separator + "order.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.close() ;	// 关闭输出流
	}
};
使用DataOutputStream写入的数据要使用DataInputStream读取进来。
import java.io.DataInputStream ;
import java.io.File ;
import java.io.FileInputStream ;
public class DataInputStreamDemo{
	public static void main(String args[]) throws Exception{	// 所有异常抛出
		DataInputStream dis = null ;		// 声明数据输入流对象
		File f = new File("d:" + File.separator + "order.txt") ; // 文件的保存路径
		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'
		try{
			while(true){
				temp = new char[200] ;	// 开辟空间
				len = 0 ;
				while((c=dis.readChar())!='\t'){	// 接收内容
					temp[len] = c ;
					len ++ ;	// 读取长度加1
				}
				name = new String(temp,0,len) ;	// 将字符数组变为String
				price = dis.readFloat() ;	// 读取价格
				dis.readChar() ;	// 读取\t
				num = dis.readInt() ;	// 读取int
				dis.readChar() ;	// 读取\n
				System.out.printf("名称:%s;价格:%5.2f;数量:%d\n",name,price,num) ;
			}
		}catch(Exception e){}
		dis.close() ;
	}
};




最后更新:2017-04-03 14:54:15

  上一篇:go [Qt教程] 第18篇 2D绘图(八)双缓冲绘图
  下一篇:go [Qt教程] 第33篇 网络(三)FTP(一)