Source of WriteMatrix1.java


  1: 
  2: import java.io.*; 
  3: 
  4: public class WriteMatrix1 {
  5: 
  6:   static double[][] data = {
  7:     { Math.exp(2.0), Math.exp(3.0), Math.exp(4.0) }, 
  8:     { Math.exp(-2.0), Math.exp(-3.0), Math.exp(-4.0) }, 
  9:   };
 10:   
 11:   public static void main(String[] args) {
 12:     int row = data.length; 
 13:     int col = data[0].length; 
 14:     int i, j; 
 15:     for (i = 0; i < row; i++) {
 16:       for (j = 0; j < col; j++) {
 17:         System.out.println("data[" + i + "][" + j + "] = " + data[i][j]);  
 18:       }
 19:     }
 20:     
 21:     if (args.length > 0) {
 22:       try { 
 23:         FileOutputStream out = new FileOutputStream(args[0]); 
 24:         writeInt(row, out); 
 25:         writeInt(col, out); 
 26:         for (i = 0; i < row; i++) {
 27:           for (j = 0; j < col; j++) {
 28:             writeDouble(data[i][j], out); 
 29:           }
 30:         }
 31:         out.close(); 
 32:       } catch (IOException e) {}  
 33:     }
 34:   }
 35: 
 36:   public static void writeInt(int i, OutputStream out) 
 37:       throws IOException {
 38:     byte[] buf = new byte[4];
 39:     for (int k = 3; k >= 0; k--) {
 40:       buf[k] = (byte)(i & 0xFF); 
 41:       i >>>= 8; 
 42:     }
 43:     out.write(buf);
 44:   }
 45: 
 46:   public static void writeDouble(double d, OutputStream out) 
 47:        throws IOException {
 48:     byte[] buf = new byte[8];
 49:     long l = Double.doubleToLongBits(d); 
 50:     for (int k = 7; k >= 0; k--) {
 51:       buf[k] = (byte)(l & 0xFF); 
 52:       l >>>= 8; 
 53:     }
 54:     out.write(buf);
 55:   }
 56: 
 57: }