在IO包中,提供了两个与平台无关的数据操作流,分别是数据输出流(DataOuputStream)和数据输入流(DataInputStream).
import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; //================================================= // File Name : DataOuputStream_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : DataOuputStream_demo; public class DataOutputStream_demo { public static void main(String[] args) throws Exception { // TODO 自动生成的方法存根 DataOutputStream dos = null; //声明数据输出流对象 File f = new File("/home/common/software/coding/HelloWord/HelloWord/order.txt");//路径 dos = new DataOutputStream(new FileOutputStream(f)); //实例化数据输出流对象 String names[] = {"衬衣","手套","围巾"}; float prices[] = {98.3f,30.0f,50.5f}; int nums[] = {3,2,1}; for(int i=0;i<names.length;i++){ //循环写入 dos.writeChars(names[i]); //写入字符串 dos.writeChar(' '); //加入分隔符 dos.writeFloat(prices[i]); //写入字符串 dos.writeChar(' '); //加入分隔符 dos.writeInt(nums[i]); //写入字符串 dos.writeChar(' '); //加入分隔符 } dos.close(); } }
读取数据
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; //================================================= // File Name : DataInputStream_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : DataInputStream_demo; public class DataInputStream_demo { public static void main(String[] args) throws Exception { // TODO 自动生成的方法存根 DataInputStream dis = null; //声明数据输出流对象 File f = new File("/home/common/software/coding/HelloWord/HelloWord/order.txt");//路径 dis = new DataInputStream(new FileInputStream(f)); //实例化数据输出流对象 String name = null; float price = 0.0f; int num = 0; char temp[] = null; char c = 0; //存放接收的字符 int len = 0; //接收的字符的个数 try{ while(true){ temp = new char[200]; len = 0; while((c=dis.readChar()) != ' '){ //读取字符 temp[len] = c; //接收内容 len++; //读取长度加1 } name = new String(temp,0,len); //将字符数组变成String price = dis.readFloat(); //读取float dis.readChar(); //读取 num = dis.readInt(); //读取int dis.readChar(); //读取 System.out.printf("名称:%s,名称:%5.2f,名称:%d ",name,price,num); } }catch(Exception e){ e.printStackTrace(); } dis.close(); } }