java 二进制文件的读写

java 二进制文件的读写:

[java] 

  1. import java.io.*;
  2. public class Demo1 {
  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args) {
  7.         // TODO Auto-generated method stub
  8.         writer();
  9.         reader();
  10.     }
  11.     static void writer(){
  12.         String filename=”c:/data1.dat”;
  13.         int value0=255,value1=0,value2=-1;
  14.         try{
  15.             DataOutputStream out=new DataOutputStream(new FileOutputStream(filename));
  16.             out.writeInt(value0);
  17.             out.writeInt(value1);
  18.             out.writeInt(value2);
  19.             out.close();
  20.         }catch(IOException io){
  21.             System.out.println(“problem writing “+filename);
  22.         }
  23.     }
  24.     static void reader(){
  25.         String filename=”c:/data1.dat”;
  26.         int sum=0;
  27.         try{
  28.             DataInputStream instr=new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
  29.             sum+=instr.readInt();
  30.             sum+=instr.readInt();
  31.             sum+=instr.readInt();
  32.             System.out.println(“this sum is :”+sum);
  33.             instr.close();
  34.         }catch(IOException iox){
  35.             System.out.println(“problem reading “+filename);
  36.         }
  37.     }
  38. }

标签