Exemplo n.º 1
1
    private static Media readMedia(DataInputStream in) throws IOException {
      String uri = in.readUTF();
      String title = readMaybeString(in);
      int width = in.readInt();
      int height = in.readInt();
      String format = in.readUTF();
      long duration = in.readLong();
      long size = in.readLong();
      boolean hasBitrate = in.readBoolean();
      int bitrate = 0;
      if (hasBitrate) bitrate = in.readInt();
      int numPersons = in.readInt();
      ArrayList<String> persons = new ArrayList<String>(numPersons);
      for (int i = 0; i < numPersons; i++) {
        persons.add(in.readUTF());
      }
      Media.Player player = Media.Player.values()[in.readByte()];
      String copyright = readMaybeString(in);

      return new Media(
          uri,
          title,
          width,
          height,
          format,
          duration,
          size,
          bitrate,
          hasBitrate,
          persons,
          player,
          copyright);
    }
Exemplo n.º 2
1
  // Loads traffic from file
  public final void load() {
    sessionInTraffic = 0;
    sessionOutTraffic = 0;
    savedCost = 0;
    lastTimeUsed = new Date(1);
    costPerDaySum = 0;
    savedSince = new Date();
    Storage traffic = new Storage("traffic");
    try {
      traffic.open(false);

      byte[] buf = traffic.getRecord(2);
      ByteArrayInputStream bais = new ByteArrayInputStream(buf);
      DataInputStream dis = new DataInputStream(bais);

      allInTraffic = dis.readInt();
      allOutTraffic = dis.readInt();
      savedSince.setTime(dis.readLong());
      lastTimeUsed.setTime(dis.readLong());
      savedCost = dis.readInt();
    } catch (Exception e) {
      savedSince.setTime(new Date().getTime());
      allInTraffic = 0;
      sessionOutTraffic = 0;
      savedCost = 0;
    }
    traffic.close();
  }
Exemplo n.º 3
1
  public void read(InputStream is) throws IOException {
    DataInputStream oin = new DataInputStream(is);
    byte[] magic = new byte[MAGIC_NUMBER.length];
    oin.read(magic, 0, magic.length);

    if (Arrays.equals(MAGIC_NUMBER_OFH_20040908, magic)) {
      // Old format requires us to read the OModel to get the type and guid.
      this.format = oin.readShort();
      this.compileTime = oin.readLong();
      oin.readInt();
      ObjectInputStream ois = new CustomObjectInputStream(_inputStream);
      OProcess oprocess;
      try {
        oprocess = (OProcess) ois.readObject();
      } catch (ClassNotFoundException e) {
        throw new IOException("DataStream Error");
      }
      this.type = new QName(oprocess.targetNamespace, oprocess.processName);
      this.guid = "OLD-FORMAT-NO-GUID";

      return;
    }
    // The current (most recent) scheme
    if (Arrays.equals(MAGIC_NUMBER, magic)) {
      this.format = oin.readShort();
      this.compileTime = oin.readLong();
      this.guid = oin.readUTF();
      String tns = oin.readUTF();
      String name = oin.readUTF();
      this.type = new QName(tns, name);
      return;
    }

    throw new IOException("Unrecognized file format (bad magic number).");
  }
Exemplo n.º 4
1
  public static MyProtocol read(InputStream in, boolean closeIO) throws IOException {
    if (in != null) {
      MyProtocol protocol = new MyProtocol();
      DataInputStream din = new DataInputStream(in);

      int version = din.readInt();
      protocol.setVersion(version);
      System.out.println(version);

      long code = din.readLong();
      protocol.setCode(code);
      System.out.println(code);

      long fUserId = din.readLong();
      protocol.setfUserId(fUserId);
      System.out.println(fUserId);

      long tUserId = din.readLong();
      protocol.settUserId(tUserId);
      System.out.println(tUserId);

      int length = din.readInt();
      protocol.setLength(length);
      System.out.println(length);

      String content = din.readUTF();
      protocol.setContent(content);
      System.out.println(content);

      if (closeIO) din.close();
      return protocol;
    }
    return null;
  }
  /**
   * Sort-based shuffle data uses an index called "shuffle_ShuffleId_MapId_0.index" into a data file
   * called "shuffle_ShuffleId_MapId_0.data". This logic is from IndexShuffleBlockResolver, and the
   * block id format is from ShuffleDataBlockId and ShuffleIndexBlockId.
   */
  private ManagedBuffer getSortBasedShuffleBlockData(
      ExecutorShuffleInfo executor, int shuffleId, int mapId, int reduceId) {
    File indexFile =
        getFile(
            executor.localDirs,
            executor.subDirsPerLocalDir,
            "shuffle_" + shuffleId + "_" + mapId + "_0.index");

    DataInputStream in = null;
    try {
      in = new DataInputStream(new FileInputStream(indexFile));
      in.skipBytes(reduceId * 8);
      long offset = in.readLong();
      long nextOffset = in.readLong();
      return new FileSegmentManagedBuffer(
          conf,
          getFile(
              executor.localDirs,
              executor.subDirsPerLocalDir,
              "shuffle_" + shuffleId + "_" + mapId + "_0.data"),
          offset,
          nextOffset - offset);
    } catch (IOException e) {
      throw new RuntimeException("Failed to open file: " + indexFile, e);
    } finally {
      if (in != null) {
        JavaUtils.closeQuietly(in);
      }
    }
  }
Exemplo n.º 6
1
 public static DatabaseArgs getArgs(String uri) throws IOException, ClassNotFoundException {
   DataInputStream in = new DataInputStream(new FileInputStream(uri));
   long firstRecordIndex = in.readLong();
   long numRecords = in.readLong();
   Configuration conf = Configuration.load(in);
   in.close();
   return getArgs(uri, conf, firstRecordIndex, numRecords, true, false);
 }
Exemplo n.º 7
1
  // Communications
  public void updateStatus(InputStream in) throws IOException {
    DataInputStream din = new DataInputStream(in);
    if (builder.length() != 0) {
      builder.delete(0, builder.length());
    }

    eventTotal.setText(form.format(new Long(din.readLong())));
    dataTotal.setText(Util.convertBytes(builder, din.readLong(), true).toString());
    builder.delete(0, builder.length());
    dataRate.setText(Util.convertBytesRate(builder, din.readDouble(), true).toString());
    eventRate.setText(form.format(new Integer((int) din.readDouble())) + "e/s");
  }
Exemplo n.º 8
1
  /**
   * Reads the payload of a tag, given the name and type.
   *
   * @param type The type.
   * @param name The name.
   * @param depth The depth.
   * @return The tag.
   * @throws IOException if an I/O error occurs.
   */
  private Tag readTagPayload(int type, String name, int depth) throws IOException {
    switch (type) {
      case NBTConstants.TYPE_END:
        if (depth == 0) {
          throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
        } else {
          return new EndTag();
        }
      case NBTConstants.TYPE_BYTE:
        return new ByteTag(name, is.readByte());
      case NBTConstants.TYPE_SHORT:
        return new ShortTag(name, is.readShort());
      case NBTConstants.TYPE_INT:
        return new IntTag(name, is.readInt());
      case NBTConstants.TYPE_LONG:
        return new LongTag(name, is.readLong());
      case NBTConstants.TYPE_FLOAT:
        return new FloatTag(name, is.readFloat());
      case NBTConstants.TYPE_DOUBLE:
        return new DoubleTag(name, is.readDouble());
      case NBTConstants.TYPE_BYTE_ARRAY:
        int length = is.readInt();
        byte[] bytes = new byte[length];
        is.readFully(bytes);
        return new ByteArrayTag(name, bytes);
      case NBTConstants.TYPE_STRING:
        length = is.readShort();
        bytes = new byte[length];
        is.readFully(bytes);
        return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
      case NBTConstants.TYPE_LIST:
        int childType = is.readByte();
        length = is.readInt();

        List<Tag> tagList = new ArrayList<Tag>();
        for (int i = 0; i < length; i++) {
          Tag tag = readTagPayload(childType, "", depth + 1);
          if (tag instanceof EndTag) {
            throw new IOException("TAG_End not permitted in a list.");
          }
          tagList.add(tag);
        }

        return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
      case NBTConstants.TYPE_COMPOUND:
        Map<String, Tag> tagMap = new HashMap<String, Tag>();
        while (true) {
          Tag tag = readTag(depth + 1);
          if (tag instanceof EndTag) {
            break;
          } else {
            tagMap.put(tag.getName(), tag);
          }
        }

        return new CompoundTag(name, tagMap);
      default:
        throw new IOException("Invalid tag type: " + type + ".");
    }
  }
Exemplo n.º 9
0
  void prepareDH() throws Exception {
    long gen = is.readLong();
    long mod = is.readLong();
    dh_resp = is.readLong();

    dh = new DH(gen, mod);
    long pub = dh.createInterKey();

    os.write(DH.longToBytes(pub));
  }
Exemplo n.º 10
0
 /**
  * 读取文件列表
  *
  * @param dis
  * @param fileTableNumber
  * @return
  * @throws Exception
  */
 public static LPKTable[] readLPKTable(DataInputStream dis, int fileTableNumber) throws Exception {
   LPKTable[] fileTable = new LPKTable[fileTableNumber];
   for (int i = 0; i < fileTableNumber; i++) {
     LPKTable ft = new LPKTable();
     ft.setFileName(readByteArray(dis, LPKHeader.LF_FILE_LENGTH));
     ft.setFileSize(dis.readLong());
     ft.setOffSet(dis.readLong());
     fileTable[i] = ft;
   }
   return fileTable;
 }
Exemplo n.º 11
0
 @Override
 public Cell decode(DataInputStream dis) throws IOException {
   Cell c = new Cell();
   try {
     c.row = dis.readLong();
   } catch (Exception e) { // EOF reached
     throw new IOException(e);
   }
   c.col = dis.readLong();
   c.content = dis.readUTF();
   return c;
 }
 public final void read(DataInputStream in) throws IOException {
   int _length = in.readShort();
   keepAliveSendTimeOut = in.readLong();
   keepAliveReceiveTimeOut = in.readLong();
   cacheThresholdPercentage = in.readByte();
   flowControlThresholdTime = in.readShort();
   minConnectionSpeed = in.readInt();
   length = 23;
   if (length != _length) {
     throw new IOException("Falsche Telegrammlänge");
   }
 }
Exemplo n.º 13
0
 public static ScoreMenu[] loadFile() {
   MainWindow.initDataFile(SCORE_MENU_FILE);
   DataInputStream input;
   Course course;
   Class tempClass;
   Student student;
   int[] testTime;
   long[] id;
   float[] score;
   ScoreMenu[] scoreMenu = new ScoreMenu[20];
   int count = 0;
   try {
     input = new DataInputStream(new FileInputStream(SCORE_MENU_FILE));
     while (input.available() > 0) {
       if (count >= scoreMenu.length) {
         ScoreMenu[] temp = new ScoreMenu[scoreMenu.length * 2];
         for (int i = 0; i < scoreMenu.length; i++) temp[i] = scoreMenu[i];
         scoreMenu = temp;
       }
       tempClass = new Class();
       tempClass.setGrade(input.readInt());
       tempClass.setMajor(input.readUTF());
       tempClass.setClassNumber(input.readInt());
       tempClass.setStudentNumber(0);
       int num = input.readInt();
       for (int i = 0; i < num; i++) {
         student = new Student();
         student.setId(input.readLong());
         student.setName(input.readUTF());
         tempClass.addStudent(student);
       }
       course = new Course();
       course.setId(input.readUTF());
       course.setName(input.readUTF());
       course.setCredit(input.readFloat());
       course.setPeriod(input.readInt());
       testTime = new int[5];
       for (int i = 0; i < 5; i++) testTime[i] = input.readInt();
       num = input.readInt();
       id = new long[num];
       score = new float[num];
       for (int i = 0; i < num; i++) id[i] = input.readLong();
       for (int i = 0; i < num; i++) score[i] = input.readFloat();
       scoreMenu[count] = new ScoreMenu(tempClass, course, testTime, num, id, score);
       count++;
     }
     input.close();
     return scoreMenu;
   } catch (Exception e) {
     return null;
   }
 }
Exemplo n.º 14
0
  public synchronized boolean recieve() {
    Socket socket = null;
    SocketChannel socketChannel = null;
    this.fObserver.setDatainput(true);
    try {
      InetAddress ia = serverName;
      InetSocketAddress isa = new InetSocketAddress(ia, port);
      System.out.println("|" + serverName + "|");
      socketChannel = SocketChannel.open(isa);
      socket = socketChannel.socket();

      DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
      String FileKey = dataInputStream.readUTF();
      long sizeInBytes = dataInputStream.readLong();
      long timeStap = dataInputStream.readLong();

      System.out.println("FileSize: " + sizeInBytes);

      File file = this.fObserver.getFile(FileKey);
      if (file == null) {
        String path = this.fObserver.getPath(FileKey);
        file = new File(path);
      }
      Utils.createParentDirectory(file);
      System.out.println(getClass() + " Fetching file... " + file);
      FileOutputStream fileOutputStream = new FileOutputStream(file);
      FileChannel fileChannel = fileOutputStream.getChannel();

      transfer(fileChannel, socketChannel, sizeInBytes, 1024 * 1024 * 16, true, false);

      fileOutputStream.close();

      file.setLastModified(timeStap);
      // System.out.println("Das Timestapsetzen hat geklappt: " + setLM +" Die Differenz ist: " +
      // (timeStap-file.lastModified()));
      socket.close();
      this.fObserver.setDatainput(false);
      return true;
    } catch (ConnectException e) {
      System.out.println("Verbindungsaufbau fehlgeschlagen. Connectiontimeout.");
      return false;
    } catch (IOException e) {
      try {
        socket.close();

      } catch (IOException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
      return false;
    }
  }
Exemplo n.º 15
0
  private void processRequest(DataInputStream in) throws IOException {

    long serverId = in.readLong();

    ServerObject server = servingById.get(serverId);

    long requestId = in.readLong();
    Request r = new Request(this, server.getObject());
    r.deserialize(in);
    r.invoke();
    if (requestId != -1) {
      sendResponse(requestId, r.getResult(), r.getResultDeclaredType());
    }
  }
Exemplo n.º 16
0
  /**
   * Read data from input stream
   *
   * @return true on success
   */
  @SuppressWarnings("unchecked")
  public boolean load(DataInputStream in) {
    try {
      chromosome = in.readUTF();
      size = in.readInt();
      if (verbose)
        Timer.showStdErr(
            "\tReading index for chromosome '" + chromosome + "' (index size: " + size + " )");

      // Sanity cgheck
      if (size < 0) return false;

      // Allocate arrays
      left = new int[size];
      right = new int[size];
      mid = new int[size];

      intersectFilePosStart = new long[size][];
      intersectFilePosEnd = new long[size][];
      intersect = new List[size];

      // Read array data
      for (int i = 0; i < size; i++) {
        left[i] = in.readInt();
        right[i] = in.readInt();
        mid[i] = in.readInt();

        int len = in.readInt();
        if (len > 0) {
          // Allocate
          intersectFilePosStart[i] = new long[len];
          intersectFilePosEnd[i] = new long[len];

          // Read values
          for (int j = 0; j < len; j++) {
            intersectFilePosStart[i][j] = in.readLong();
            intersectFilePosEnd[i][j] = in.readLong();
          }
        } else {
          intersectFilePosStart[i] = intersectFilePosEnd[i] = null;
        }
      }
    } catch (EOFException e) {
      return false;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    return true;
  }
Exemplo n.º 17
0
  public void readIn(DataInputStream din) throws IOException {
    lastActive = din.readLong();
    inBytes = din.readLong();
    outBytes = din.readLong();
    total = din.readLong();
    rmt_ip = din.readLong();
    lcl_port = din.readInt();
    rmt_port = din.readInt();

    for (int i = 0; i < tfPercent.length; ++i) {
      int num = (int) (din.readByte() & 0xFF);
      tfPercent[i] = ((double) num) / 100.0;
    }
  }
Exemplo n.º 18
0
  public long readLong() throws IOException {
    updateMetricReceivedBytes(OBinaryProtocol.SIZE_LONG);

    if (debug) {
      OLogManager.instance()
          .info(this, "%s - Reading long (8 bytes)...", socket.getRemoteSocketAddress());
      final long value = in.readLong();
      OLogManager.instance()
          .info(this, "%s - Read long: %d", socket.getRemoteSocketAddress(), value);
      return value;
    }

    return in.readLong();
  }
  /**
   * Método auxiliar que gerar uma Coleção de Dados da Movimentação
   *
   * @param data
   * @return
   * @throws IOException
   */
  private Collection<DadosMovimentacao> gerarColecaoDadosMovimentacao(
      DataInputStream data, Long imei) throws IOException {
    Collection<DadosMovimentacao> dados = new ArrayList<DadosMovimentacao>();
    int imovel = data.read();
    while (imovel != -1) {

      byte[] b = new byte[4];
      b[0] = (byte) imovel;
      b[1] = (byte) data.read();
      b[2] = (byte) data.read();
      b[3] = (byte) data.read();

      dados.add(
          new DadosMovimentacao(
              new Integer(this.convertArrayByteToInt(b)),
              new Integer(data.readInt()),
              new Integer(data.readByte()),
              new Date(data.readLong()),
              imei,
              new Byte(data.readByte()),
              new Integer(data.readInt())));

      // System.out.println("imovel=" + data.read());
      imovel = data.read();
    }
    return dados;
  }
  /**
   * Método de Comfirmação do Recebimento do Arquivo
   *
   * @since 23/05/08
   * @param data
   * @throws IOException
   */
  public void confirmacaoArquivoRecebido(DataInputStream data) throws IOException {
    Fachada fachada = Fachada.getInstancia();
    long imei = data.readLong();

    System.out.println("Confirmando Recebimento do arquivo Mobile imei = " + imei);

    // Atualiza a situação do arquivo texto de "em campo" para "finalizado e não transmitido"
    // Alteração feita por Sávio Luiz
    // Data:05/04/2010
    fachada.atualizarArquivoTextoEnviado(
        imei,
        SituacaoTransmissaoLeitura.EM_CAMPO,
        SituacaoTransmissaoLeitura.FINALIZADO_NAO_TRANSMITIDO);

    // Atualiza a situação do arquivo texto de "liberado" para "em campo"
    // Alteração feita por Sávio Luiz
    // Data:05/04/2010
    fachada.atualizarArquivoTextoEnviado(
        imei, SituacaoTransmissaoLeitura.LIBERADO, SituacaoTransmissaoLeitura.EM_CAMPO);

    // Atualiza a situação do arquivo texto de "disponível" para "liberado"
    // Alteração feita por Sávio Luiz
    // Data:05/04/2010
    fachada.atualizarArquivoTextoMenorSequencialLeitura(
        imei,
        SituacaoTransmissaoLeitura.DISPONIVEL,
        SituacaoTransmissaoLeitura.LIBERADO,
        ServicoTipoCelular.LEITURA);
  }
 @Nullable
 private DataInputStream createFSDataStream(File dataStorageRoot) {
   if (myInitialFSDelta == null) {
     // this will force FS rescan
     return null;
   }
   try {
     final File file = new File(dataStorageRoot, FS_STATE_FILE);
     final InputStream fs = new FileInputStream(file);
     byte[] bytes;
     try {
       bytes = FileUtil.loadBytes(fs, (int) file.length());
     } finally {
       fs.close();
     }
     final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
     final int version = in.readInt();
     if (version != FSState.VERSION) {
       return null;
     }
     final long savedOrdinal = in.readLong();
     if (savedOrdinal + 1L != myInitialFSDelta.getOrdinal()) {
       return null;
     }
     return in;
   } catch (FileNotFoundException ignored) {
   } catch (Throwable e) {
     LOG.error(e);
   }
   return null;
 }
Exemplo n.º 22
0
 protected long readLong() {
   try {
     return inputStream.readLong();
   } catch (IOException e) {
     return 0;
   }
 }
Exemplo n.º 23
0
  private static void primitiveTypes() {
    try (DataOutputStream dataOutputStream =
        new DataOutputStream(new FileOutputStream("d:/myData.dat"))) {
      long[] longs = new long[] {1, 2, 3, 5, 4};

      for (long aLong : longs) {
        dataOutputStream.writeLong(aLong);
      }
    } catch (IOException e) {
      System.out.println(e);
    }

    try (DataInputStream dataInputStream =
        new DataInputStream(new FileInputStream("d:/myData.dat"))) {
      try {
        while (true) {
          System.out.println(dataInputStream.readLong());
        }
      } catch (EOFException e) {
        System.out.println("end");
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
  private void loadRMDTSecretManagerState(RMState rmState) throws Exception {
    FileStatus[] childNodes = fs.listStatus(rmDTSecretManagerRoot);

    for (FileStatus childNodeStatus : childNodes) {
      assert childNodeStatus.isFile();
      String childNodeName = childNodeStatus.getPath().getName();
      if (childNodeName.startsWith(DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX)) {
        rmState.rmSecretManagerState.dtSequenceNumber =
            Integer.parseInt(childNodeName.split("_")[1]);
        continue;
      }

      Path childNodePath = getNodePath(rmDTSecretManagerRoot, childNodeName);
      byte[] childData = readFile(childNodePath, childNodeStatus.getLen());
      ByteArrayInputStream is = new ByteArrayInputStream(childData);
      DataInputStream fsIn = new DataInputStream(is);
      if (childNodeName.startsWith(DELEGATION_KEY_PREFIX)) {
        DelegationKey key = new DelegationKey();
        key.readFields(fsIn);
        rmState.rmSecretManagerState.masterKeyState.add(key);
      } else if (childNodeName.startsWith(DELEGATION_TOKEN_PREFIX)) {
        RMDelegationTokenIdentifier identifier = new RMDelegationTokenIdentifier();
        identifier.readFields(fsIn);
        long renewDate = fsIn.readLong();
        rmState.rmSecretManagerState.delegationTokenState.put(identifier, renewDate);
      } else {
        LOG.warn("Unknown file for recovering RMDelegationTokenSecretManager");
      }
      fsIn.close();
    }
  }
Exemplo n.º 25
0
 /** @return first 8 bytes of hash; -1 on Error */
 public long truncHash() throws IOException {
   if (hash != null && hash.length >= 8) {
     DataInputStream dis = new DataInputStream(new ByteArrayInputStream(hash));
     return dis.readLong();
   }
   return -1;
 }
Exemplo n.º 26
0
 /**
  * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code
  * BloomFilter<T>}.
  *
  * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
  * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
  * the original Bloom filter!
  *
  * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
  *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
  */
 public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<T> funnel) throws IOException {
   checkNotNull(in, "InputStream");
   checkNotNull(funnel, "Funnel");
   int strategyOrdinal = -1;
   int numHashFunctions = -1;
   int dataLength = -1;
   try {
     DataInputStream din = new DataInputStream(in);
     // currently this assumes there is no negative ordinal; will have to be updated if we
     // add non-stateless strategies (for which we've reserved negative ordinals; see
     // Strategy.ordinal()).
     strategyOrdinal = din.readByte();
     numHashFunctions = UnsignedBytes.toInt(din.readByte());
     dataLength = din.readInt();
     Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal];
     long[] data = new long[dataLength];
     for (int i = 0; i < data.length; i++) {
       data[i] = din.readLong();
     }
     return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
   } catch (RuntimeException e) {
     IOException ioException =
         new IOException(
             "Unable to deserialize BloomFilter from InputStream."
                 + " strategyOrdinal: "
                 + strategyOrdinal
                 + " numHashFunctions: "
                 + numHashFunctions
                 + " dataLength: "
                 + dataLength);
     ioException.initCause(e);
     throw ioException;
   }
 }
Exemplo n.º 27
0
  public void readRS() {
    RecordStore rs = null;
    try {
      rs = RecordStore.openRecordStore("score", true);
      byte[] byteA = new byte[100];

      list.removeAllElements();
      // System.out.println("size of list before reading out of rs: "+ list.size());
      for (int i = 1; i < 6; i++) {
        byteA = rs.getRecord(i);
        // System.out.println((char) byteA[0]);
        // System.out.println("1");
        ByteArrayInputStream bytes = new ByteArrayInputStream(byteA);
        // System.out.println("2");
        DataInputStream dataIn = new DataInputStream(bytes);
        // System.out.println("3");
        try {
          list.addElement(
              new ScoreItem(
                  dataIn.readUTF(), dataIn.readInt(), dataIn.readInt(), dataIn.readLong()));
        } catch (IOException exp) {
        }
      }
      // System.out.println("size of list after reading out of rs: "+ list.size());
      rs.closeRecordStore();
    } catch (RecordStoreException exp) {
      System.out.println("fehler: " + exp.toString());
      exp.printStackTrace();
    }
  }
Exemplo n.º 28
0
  public static void main(String[] args) throws IOException {
    // Create a FileOutputStream.
    FileOutputStream outputFile = new FileOutputStream("primitives.data");

    // Create a DataOutputStream which is chained to the FileOutputStream.
    DataOutputStream outputStream = new DataOutputStream(outputFile);

    // Write Java primitive values in binary representation:
    outputStream.writeBoolean(true);
    outputStream.writeChar('A'); // int written as Unicode char
    outputStream.writeByte(Byte.MAX_VALUE); // int written as 8-bits byte
    outputStream.writeShort(Short.MIN_VALUE); // int written as 16-bits short
    outputStream.writeInt(Integer.MAX_VALUE);
    outputStream.writeLong(Long.MIN_VALUE);
    outputStream.writeFloat(Float.MAX_VALUE);
    outputStream.writeDouble(Math.PI);

    // Close the output stream, which also closes the underlying stream.
    outputStream.flush();
    outputStream.close();

    // Create a FileInputStream.
    FileInputStream inputFile = new FileInputStream("primitives.data");

    // Create a DataInputStream which is chained to the FileInputStream.
    DataInputStream inputStream = new DataInputStream(inputFile);

    // Read the binary representation of Java primitive values
    // in the same order they were written out:
    boolean v = inputStream.readBoolean();
    char c = inputStream.readChar();
    byte b = inputStream.readByte();
    short s = inputStream.readShort();
    int i = inputStream.readInt();
    long l = inputStream.readLong();
    float f = inputStream.readFloat();
    double d = inputStream.readDouble();

    // Check for end of stream:
    try {
      int value = inputStream.readByte();
      System.out.println("More input: " + value);
    } catch (EOFException eofe) {
      System.out.println("End of stream");
    } finally {
      // Close the input stream, which also closes the underlying stream.
      inputStream.close();
    }

    // Write the values read to the standard input stream:
    System.out.println("Values read:");
    System.out.println(v);
    System.out.println(c);
    System.out.println(b);
    System.out.println(s);
    System.out.println(i);
    System.out.println(l);
    System.out.println(f);
    System.out.println(d);
  }
Exemplo n.º 29
0
  /**
   * Unpack received message and fill the structure
   *
   * @param cliId corresponding client identifier
   * @param rawdata network message
   * @throws MeasurementError stream reader failed
   */
  public MeasurementPacket(ClientIdentifier cliId, byte[] rawdata) throws MeasurementError {
    this.clientId = cliId;

    ByteArrayInputStream byteIn = new ByteArrayInputStream(rawdata);
    DataInputStream dataIn = new DataInputStream(byteIn);

    try {
      type = dataIn.readInt();
      burstCount = dataIn.readInt();
      packetNum = dataIn.readInt();
      intervalNum = dataIn.readInt();
      timestamp = dataIn.readLong();
      packetSize = dataIn.readInt();
      seq = dataIn.readInt();
      udpInterval = dataIn.readInt();
    } catch (IOException e) {
      throw new MeasurementError("Fetch payload failed! " + e.getMessage());
    }

    try {
      byteIn.close();
    } catch (IOException e) {
      throw new MeasurementError("Error closing inputstream!");
    }
  }
Exemplo n.º 30
0
  public static void main(String[] args) {

    String inputFileName =
        "C:\\Users\\Ahmed\\Desktop\\RA\\2011-2012\\Term1\\KNN\\BerlinMod Data\\trips.1000.dat";

    FileInputStream fin;
    try {
      fin = new FileInputStream(inputFileName);
      DataInputStream din = new DataInputStream(fin);

      while (true)
        System.out.println(
            din.readInt()
                + ", "
                + din.readLong()
                + ", "
                + din.readDouble()
                + ", "
                + din.readDouble());

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.out.println("End of file reached");
      e.printStackTrace();
    }
  }