⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dataioexam.java

📁 Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程序均在JDK1.6环境下编译运行正常,除了第13章需要建立ODBC数据源之外,其他程序只要有Java运行环境即可直接运行
💻 JAVA
字号:
import java.io.*;
public class DataIOExam {
  public static void main(String[] args) throws IOException {
    //创建数据输出流
    DataOutputStream out = new DataOutputStream(new FileOutputStream("my.dat"));
    //初始化输出数据
    double[] prices = {19.95, 9.90, 15.15, 3.45, 4.37};
    int[] units = {12, 8, 13, 26, 50};
    String[] products = {"APPLE","PEA","TOMATO","PEACH","BREAD" };
    //数据输出
    for (int i = 0; i < prices.length; i++) {
      out.writeDouble(prices[i]);
      out.writeChar('\t');
      out.writeInt(units[i]);
      out.writeChar('\t');
      out.writeBytes(products[i]);
      out.writeChar('\n');
    }
    //关闭数据输出流
    out.close();
    //创建数据输入流
    DataInputStream in = new DataInputStream(new FileInputStream("my.dat"));

    double price;
    int unit;
    String prod;
    double total = 0.0;
    try {
    	int i = 0;
      //利用数据输入流读文件内容
      while (i++<5) { //根据写入内容读取,如果不设置循环条件,将抛出异常
        price = in.readDouble();
        in.readChar(); // throws out the tab
        unit = in.readInt();
        in.readChar(); // throws out the tab
        prod = in.readLine();
        System.out.println("产品:" + prod + "价格:$" + price + " 数量:" + unit);
        total = total + unit * price;
      }
    }
    //捕获异常
    catch (EOFException e) {
      e.printStackTrace();
    }
    System.out.println("金额合计: $" + total);
    //关闭数据输入流
    in.close();
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -