应用实例importjava.io.*;publiccla"/>

java 数据流DataOutputStream和DataInputstream

Posted mqxnongmin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 数据流DataOutputStream和DataInputstream相关的知识,希望对你有一定的参考价值。

java流操作类的认识和总结

技术图片

应用实例

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;
	}
}
技术图片

以上是关于java 数据流DataOutputStream和DataInputstream的主要内容,如果未能解决你的问题,请参考以下文章

JAVA IO操作:数据操作流:DataOutputStream和DataInputStream

Java IO DataInputStream 和 DataOutputStream

JAVA DataOutputStream和DataInputStream

java 数据流DataOutputStream和DataInputstream

Java IO中的数据输出流(DataOutputStream)和普通输出流(OutputStre

DataInputStream和DataOutputStream