WHCSRL 技术网

java dataoutputstream_java 数据流DataOutputStream和DataInputstream

SouthEast

应用实例

import java.io.*;

public class DataStreamDemo

{undefined

public static void main(String[] args)

{undefined

try

{undefined

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

{undefined

try

{undefined

out.writeDouble(prices[i]);

out.writeChar('\t');

out.writeInt(units[i]);

out.writeChar('\t');

out.writeChars(descs[i]);

out.writeChar('\n');

}

catch (IOException e)

{undefined

// TODO Auto-generated catch block

e.printStackTrace();

}

}

try

{undefined

out.close();

}

catch (IOException e)

{undefined

// TODO Auto-generated catch block

e.printStackTrace();

}

}

catch (FileNotFoundException e)

{undefined

// TODO Auto-generated catch block

e.printStackTrace();

}

try

{undefined

DataInputStream in=new DataInputStream(new FileInputStream("F:\\workspace\\JavaPrj\\test.txt"));

double prices;

int num;

StringBuffer name;

char chr;

int len;

try

{undefined

while(true)

{undefined

len=5;

name=new StringBuffer();

prices=in.readDouble();

in.readChar();

num=in.readInt();

in.readChar();

while((chr=in.readChar())!='\n')

{undefined

name.append(chr);

}

//double类型转String类型以及加入空格对齐的方法

System.out.println("产品名称:"+name+"\t价格:"+prices+getBlanks(len-Double.toString(prices).length())+"\t数量:"+num);

}

}

catch (IOException e)

{undefined

// TODO Auto-generated catch block

e.printStackTrace();

}

}

catch (FileNotFoundException e)

{undefined

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//加入空格进行对齐操作

public static String getBlanks(int n)

{undefined

String str="";

while(n>0)

{undefined

str+=" ";

n--;

}

return str;

}

}

e9a8da7b3d8c719ec160bfab9d9ba607.png

推荐阅读