服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用datastream 读写文件之二

使用datastream 读写文件之二


/* from http://java.sun.com/docs/books/tutorial/index.html */


import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.eofexception;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;

public class dataiotest {
  public static void main(string[] argsthrows ioexception {

    // write the data out
    dataoutputstream out = new dataoutputstream(new fileoutputstream(
        "invoice1.txt"));

    double[] prices = 19.999.9915.993.994.99 };
    int[] units = 128132950 };
    string[] descs = "java t-shirt""java mug""duke juggling dolls",
        "java pin""java key chain" };

    for (int i = 0; i < prices.length; i++) {
      out.writedouble(prices[i]);
      out.writechar('/t');
      out.writeint(units[i]);
      out.writechar('/t');
      out.writechars(descs[i]);
      out.writechar('/n');
    }
    out.close();

    // read it in again
    datainputstream in = new datainputstream(new fileinputstream(
        "invoice1.txt"));

    double price;
    int unit;
    stringbuffer desc;
    double total = 0.0;

    try {
      while (true) {
        price = in.readdouble();
        in.readchar()// throws out the tab
        unit = in.readint();
        in.readchar()// throws out the tab
        char chr;
        desc = new stringbuffer(20);
        char linesep = system.getproperty("line.separator").charat(0);
        while ((chr = in.readchar()) != linesep)
          desc.append(chr);
        system.out.println("you've ordered " + unit + " units of "
            + desc + " at $" + price);
        total = total + unit * price;
      }
    catch (eofexception e) {
    }
    system.out.println("for a total of: $" + total);
    in.close();
  }
}
           

扫描关注微信公众号