码迷,mamicode.com
首页 > 编程语言 > 详细

java DataOutputStream和DataInputstream

时间:2014-05-03 15:38:36      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:java   dataoutputsream   datainputsream   

java流操作类的认识和总结

bubuko.com,布布扣

应用实例

import java.io.*;

public class DataStreamDemo
{
	public static void main(String[] args)
	{
		try 
		{
			DataOutputStream out=new DataOutputStream(new FileOutputStream("F:\\workspace\\JavaPrj\\test.txt"));
			double[] prices={18.99,9.22,14.22,5.22,4.21};
			int[] units={10,10,20,39,40};
			String[] descs={"bike","book","boat","boot","bus"};
			for(int i=0;i<prices.length;i++)
			{
				try 
				{
					out.writeDouble(prices[i]);
					out.writeChar(‘\t‘);
					out.writeInt(units[i]);
					out.writeChar(‘\t‘);
					out.writeChars(descs[i]);
					out.writeChar(‘\n‘);
				} 
				catch (IOException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			try 
			{
				out.close();
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try 
		{
			DataInputStream in=new DataInputStream(new FileInputStream("F:\\workspace\\JavaPrj\\test.txt"));
			double prices;
			int num;
			StringBuffer name;
			char chr;
			int len;
			
			try 
			{
				while(true)
				{
					len=5;
					name=new StringBuffer();
					prices=in.readDouble();
					in.readChar();
					num=in.readInt();
					in.readChar();
					while((chr=in.readChar())!=‘\n‘)
					{
						name.append(chr);
					}
					//double类型转String类型以及添加空格对齐的方法
					System.out.println("产品名称:"+name+"\t价格:"+prices+getBlanks(len-Double.toString(prices).length())+"\t数量:"+num);
				} 
			}
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//添加空格进行对齐操作
	public static String getBlanks(int n)
	{
		String str="";
		while(n>0)
		{
			str+=" ";
			n--;
		}
		return str;
	}
}
bubuko.com,布布扣

java DataOutputStream和DataInputstream,布布扣,bubuko.com

java DataOutputStream和DataInputstream

标签:java   dataoutputsream   datainputsream   

原文地址:http://blog.csdn.net/cjc211322/article/details/24905937

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!