Ejemplo n.º 1
0
  /**
   * Stops the recording, and sets the state to STOPPED. In case of further usage, a reset is
   * needed. Also finalizes the wave file in case of uncompressed recording.
   */
  public void stop() {
    if (state == State.RECORDING) {
      if (rUncompressed) {
        audioRecorder.stop();

        try {
          randomAccessWriter.seek(4); // Write size to RIFF header
          randomAccessWriter.writeInt(Integer.reverseBytes(36 + payloadSize));

          randomAccessWriter.seek(40); // Write size to Subchunk2Size field
          randomAccessWriter.writeInt(Integer.reverseBytes(payloadSize));

          randomAccessWriter.close();
        } catch (IOException e) {
          Log.e(
              ExtAudioRecorder.class.getName(), "I/O exception occured while closing output file");
          state = State.ERROR;
        }
      } else {
        mediaRecorder.stop();
      }
      state = State.STOPPED;
    } else {
      Log.e(ExtAudioRecorder.class.getName(), "stop() called on illegal state");
      state = State.ERROR;
    }
  }
Ejemplo n.º 2
0
  /**
   * Prepares the recorder for recording, in case the recorder is not in the INITIALIZING state and
   * the file path was not set the recorder is set to the ERROR state, which makes a reconstruction
   * necessary. In case uncompressed recording is toggled, the header of the wave file is written.
   * In case of an exception, the state is changed to ERROR
   */
  public void prepare() {
    try {
      if (state == State.INITIALIZING) {
        if (rUncompressed) {
          if ((audioRecorder.getState() == AudioRecord.STATE_INITIALIZED) & (filePath != null)) {
            // write file header

            randomAccessWriter = new RandomAccessFile(filePath, "rw");

            randomAccessWriter.setLength(
                0); // Set file length to 0, to prevent unexpected behavior in case the file already
                    // existed
            randomAccessWriter.writeBytes("RIFF");
            randomAccessWriter.writeInt(0); // Final file size not known yet, write 0
            randomAccessWriter.writeBytes("WAVE");
            randomAccessWriter.writeBytes("fmt ");
            randomAccessWriter.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
            randomAccessWriter.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
            randomAccessWriter.writeShort(
                Short.reverseBytes(nChannels)); // Number of channels, 1 for mono, 2 for stereo
            randomAccessWriter.writeInt(Integer.reverseBytes(sRate)); // Sample rate
            randomAccessWriter.writeInt(
                Integer.reverseBytes(
                    sRate * bSamples * nChannels
                        / 8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
            randomAccessWriter.writeShort(
                Short.reverseBytes(
                    (short)
                        (nChannels * bSamples
                            / 8))); // Block align, NumberOfChannels*BitsPerSample/8
            randomAccessWriter.writeShort(Short.reverseBytes(bSamples)); // Bits per sample
            randomAccessWriter.writeBytes("data");
            randomAccessWriter.writeInt(0); // Data chunk size not known yet, write 0

            buffer = new byte[framePeriod * bSamples / 8 * nChannels];
            state = State.READY;
          } else {
            Log.e(
                ExtAudioRecorder.class.getName(),
                "prepare() method called on uninitialized recorder");
            state = State.ERROR;
          }
        } else {
          mediaRecorder.prepare();
          state = State.READY;
        }
      } else {
        Log.e(ExtAudioRecorder.class.getName(), "prepare() method called on illegal state");
        release();
        state = State.ERROR;
      }
    } catch (Exception e) {
      if (e.getMessage() != null) {
        Log.e(ExtAudioRecorder.class.getName(), e.getMessage());
      } else {
        Log.e(ExtAudioRecorder.class.getName(), "Unknown error occured in prepare()");
      }
      state = State.ERROR;
    }
  }
Ejemplo n.º 3
0
 /*
  * Writes WAV header into new file.
  */
 private void writeWavHeader() {
   try {
     randomAccessWriter = new RandomAccessFile(filePath, "rw");
     randomAccessWriter.setLength(0);
     randomAccessWriter.writeBytes("RIFF");
     randomAccessWriter.writeInt(0); // Final file size not known yet, write 0
     randomAccessWriter.writeBytes("WAVE");
     randomAccessWriter.writeBytes("fmt ");
     randomAccessWriter.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
     randomAccessWriter.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
     randomAccessWriter.writeShort(
         Short.reverseBytes((short) 1)); // Number of channels, 1 for mono, 2 for stereo
     randomAccessWriter.writeInt(Integer.reverseBytes(RECORDER_SAMPLE_RATE)); // Sample rate
     randomAccessWriter.writeInt(
         Integer.reverseBytes(
             RECORDER_SAMPLE_RATE
                 * 16
                 * 1
                 / 8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
     randomAccessWriter.writeShort(
         Short.reverseBytes(
             (short) (1 * 16 / 8))); // Block align, NumberOfChannels*BitsPerSample/8
     randomAccessWriter.writeShort(Short.reverseBytes((short) 16)); // Bits per sample
     randomAccessWriter.writeBytes("data");
     randomAccessWriter.writeInt(0); // Data chunk size not known yet, write 0
   } catch (Exception e) {
     Log.e("Microphone", "Error writing WAV header.");
   }
 }
Ejemplo n.º 4
0
 public void saveMetaData() throws IOException {
   pageFile.seek(offset);
   pageFile.writeInt(nextPageId);
   pageFile.writeInt(currentFill);
   pageFile.writeInt(bloomfilter);
   pageFile.writeByte(type);
 }
Ejemplo n.º 5
0
 public void writeTo(final RandomAccessFile raf) throws IOException {
   raf.write(type.getBytes(Charsets.US_ASCII));
   raf.writeInt(version);
   raf.writeInt(metaData.length);
   if (metaData.length > 0) {
     raf.write(metaData);
   }
 }
Ejemplo n.º 6
0
  private static RegionFile fixNegativeOffset(File regionFileFile) {
    FMLLog.log(
        Level.WARNING,
        "Region file " + regionFileFile + " is corrupted: negative offset. Attempting to fix.");
    try {
      Files.copy(
          regionFileFile,
          new File(regionFileFile.getParentFile(), regionFileFile.getName() + ".bak"));
    } catch (IOException e) {
      FMLLog.log(Level.SEVERE, e, "Failed to back up corrupt region file.");
    }
    try {
      RandomAccessFile dataFile = new RandomAccessFile(regionFileFile, "rw");
      try {
        int length;

        if (dataFile.length() < 4096L) {
          for (length = 0; length < 1024; ++length) {
            dataFile.writeInt(0);
          }

          for (length = 0; length < 1024; ++length) {
            dataFile.writeInt(0);
          }
        }

        if ((dataFile.length() & 4095L) != 0L) {
          for (length = 0; (long) length < (dataFile.length() & 4095L); ++length) {
            dataFile.write(0);
          }
        }

        length = (int) dataFile.length() / 4096;

        dataFile.seek(0L);

        for (int i = 0; i < 1024; ++i) {
          int offset = dataFile.readInt();

          if (offset != 0 && (offset >> 8) + (offset & 255) <= length) {
            for (int var5 = 0; var5 < (offset & 255); ++var5) {
              if ((offset >> 8) + var5 < 0) {
                dataFile.seek(dataFile.getFilePointer() - 4);
                dataFile.writeInt(0);
                break;
              }
            }
          }
        }
      } finally {
        dataFile.close();
      }
    } catch (Throwable t) {
      FMLLog.log(Level.SEVERE, t, "Failed to fix negative offset index in " + regionFileFile);
      throw UnsafeUtil.throwIgnoreChecked(t);
    }
    return new RegionFile(regionFileFile);
  }
 public void write(RandomAccessFile raf) throws IOException {
   raf.writeUTF(token);
   raf.writeInt(startRow);
   raf.writeInt(numRows);
   final boolean hasNormalizedForm = !token.equals(normalizedToken);
   raf.writeBoolean(hasNormalizedForm);
   if (hasNormalizedForm) {
     raf.writeUTF(normalizedToken);
   }
   RAFList.write(raf, htmlEntries, index.dict.htmlEntryIndexSerializer);
 }
Ejemplo n.º 8
0
 /** @return the remaining space in bytes */
 protected void writeHeader(RandomAccessFile file, long length, int segmentSize)
     throws IOException {
   file.seek(0);
   file.writeUTF("GH");
   // make changes to file format only with major version changes
   file.writeInt(version());
   file.writeLong(length);
   file.writeInt(segmentSize);
   for (int i = 0; i < header.length; i++) {
     file.writeInt(header[i]);
   }
 }
Ejemplo n.º 9
0
  // "parent" is the AbstractID3-derived instance making use of this frame.
  public void write(final RandomAccessFile file, AbstractID3 parent) throws IOException {
    final String str;
    final Iterator<?> iterator;
    final byte[] buffer = new byte[6];
    final MP3File mp3 = new MP3File();
    mp3.seekMP3Frame(file);
    final long mp3start = file.getFilePointer();
    file.seek(0);
    ID3v2_3Frame frame;
    str = "ID3";
    for (int i = 0; i < str.length(); i++) {
      buffer[i] = (byte) str.charAt(i);
    }
    buffer[3] = 3;
    buffer[4] = 0;
    if (this.unsynchronization) {
      buffer[5] |= TagConstant.MASK_V23_UNSYNCHRONIZATION;
    }
    if (this.extended) {
      buffer[5] |= TagConstant.MASK_V23_EXTENDED_HEADER;
    }
    if (this.experimental) {
      buffer[5] |= TagConstant.MASK_V23_EXPERIMENTAL;
    }
    file.write(buffer);

    // write size
    file.write(sizeToByteArray((int) mp3start - 10));
    if (this.extended) {
      if (this.crcDataFlag) {
        file.writeInt(10);
        buffer[0] = 0;
        buffer[0] |= TagConstant.MASK_V23_CRC_DATA_PRESENT;
        file.write(buffer, 0, 2);
        file.writeInt(this.paddingSize);
        file.writeInt(this.crcData);
      } else {
        file.writeInt(6);
        file.write(buffer, 0, 2);
        file.writeInt(this.paddingSize);
      }
    }

    // write all frames
    iterator = this.getFrameIterator();
    while (iterator.hasNext()) {
      frame = (ID3v2_3Frame) iterator.next();
      frame.write(file, parent);
    }
  }
Ejemplo n.º 10
0
 /* write a chunk data to the region file at specified sector number */
 private void write(int sectorNumber, byte[] data, int length) throws IOException {
   debugln(" " + sectorNumber);
   file.seek(sectorNumber * SECTOR_BYTES);
   file.writeInt(length + 1); // chunk length
   file.writeByte(VERSION_DEFLATE); // chunk version number
   file.write(data, 0, length); // chunk data
 }
Ejemplo n.º 11
0
  private int internalWriteElement(RandomAccessFile randomSerializeFile, long offset, E element)
      throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(bos);
    ObjectOutputStream out = new ObjectOutputStream(gos);
    out.writeObject(element);
    out.flush();
    out.close();
    gos.finish();
    byte[] buffer = bos.toByteArray();
    // int uncompressed=cos.getCount();

    int bufferSize = buffer.length;
    /*
    if(logger.isDebugEnabled())
    {
    	int packedPercent=(int)(((double)bufferSize/(double)uncompressed)*100f);
    	logger.debug("Uncompressed size: {}", uncompressed);
    	logger.debug("Compressed size  : {} ({}%)", bufferSize, packedPercent);
    }
    */
    randomSerializeFile.seek(offset);
    randomSerializeFile.writeInt(bufferSize);
    randomSerializeFile.write(buffer);
    return bufferSize;
  }
Ejemplo n.º 12
0
  public int bubbleSort() throws Exception {
    boolean swapped = true;
    int j = 0;
    int counter = 0;

    while (swapped) {
      swapped = false;
      j++;

      for (int i = 0; i < length() - j; i++) {
        file.seek(i * 4);
        int one = file.readInt();
        int two = file.readInt();

        if (one > two) {
          file.seek(i * 4);
          file.writeInt(two);
          file.writeInt(one);
          swapped = true;
          counter++;
        }
      }
    }
    return counter;
  }
Ejemplo n.º 13
0
  /**
   * Writes the Item ID to the Items Random Access File
   *
   * @param file - the Items Random Access File
   */
  private void writeIDToFile(RandomAccessFile file) {
    try {
      file.getFilePointer();
      file.writeInt(getID());
    } catch (Exception e) {

    }
  }
 public static void writeArray(String s, int[] x) {
   try {
     RandomAccessFile output = new RandomAccessFile(s, "rw");
     for (int i = 0; i < x.length; i++) output.writeInt(x[i]);
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
Ejemplo n.º 15
0
 private void append(SingleHit[] hits, String prefix, int chrom) throws IOException {
   RandomAccessFile positionsRAF = new RandomAccessFile(getPositionsFname(prefix, chrom), "rw");
   RandomAccessFile weightsRAF = new RandomAccessFile(getWeightsFname(prefix, chrom), "rw");
   RandomAccessFile lasRAF = new RandomAccessFile(getLaSFname(prefix, chrom), "rw");
   positionsRAF.seek(positionsRAF.length());
   weightsRAF.seek(weightsRAF.length());
   lasRAF.seek(lasRAF.length());
   for (int i = 0; i < hits.length; i++) {
     SingleHit h = hits[i];
     positionsRAF.writeInt(h.pos);
     weightsRAF.writeFloat(h.weight);
     lasRAF.writeInt(makeLAS(h.length, h.strand));
   }
   positionsRAF.close();
   weightsRAF.close();
   lasRAF.close();
 }
Ejemplo n.º 16
0
 private void writeToDataBase(final RandomAccessFile dbFile, final String word) throws MapExcept {
   try {
     dbFile.writeInt(word.getBytes("UTF-8").length);
     dbFile.write(word.getBytes("UTF-8"));
   } catch (Exception ex) {
     throw new MapExcept("can't write in file");
   }
 }
 /** Corrupt an edit log file after the start segment transaction */
 private void corruptAfterStartSegment(File f) throws IOException {
   RandomAccessFile raf = new RandomAccessFile(f, "rw");
   raf.seek(0x16); // skip version and first tranaction and a bit of next transaction
   for (int i = 0; i < 1000; i++) {
     raf.writeInt(0xdeadbeef);
   }
   raf.close();
 }
Ejemplo n.º 18
0
 private void write(String partnum, String partdesc, int qty, int ucost) throws IOException {
   StringBuffer sb = new StringBuffer(partnum);
   if (sb.length() > PNUMLEN) sb.setLength(PNUMLEN);
   else if (sb.length() < PNUMLEN) {
     int len = PNUMLEN - sb.length();
     for (int i = 0; i < len; i++) sb.append(" ");
   }
   raf.writeChars(sb.toString());
   sb = new StringBuffer(partdesc);
   if (sb.length() > DESCLEN) sb.setLength(DESCLEN);
   else if (sb.length() < DESCLEN) {
     int len = DESCLEN - sb.length();
     for (int i = 0; i < len; i++) sb.append(" ");
   }
   raf.writeChars(sb.toString());
   raf.writeInt(qty);
   raf.writeInt(ucost);
 }
Ejemplo n.º 19
0
 private void writeIntoFile(int numOfDir, int numOfFile) {
   String dirString = String.valueOf(numOfDir) + ".dir";
   String fileString = String.valueOf(numOfFile) + ".dat";
   File dbDir = tableDir.toPath().resolve(dirString).normalize().toFile();
   if (!dbDir.isDirectory()) {
     dbDir.mkdir();
   }
   File dbFile = dbDir.toPath().resolve(fileString).normalize().toFile();
   if (list[numOfDir][numOfFile].isEmpty()) {
     dbFile.delete();
     if (dbDir.list().length == 0) {
       dbDir.delete();
     }
     return;
   }
   RandomAccessFile db;
   try {
     db = new RandomAccessFile(dbFile, "rw");
     try {
       db.setLength(0);
       Iterator<Map.Entry<String, String>> it;
       it = list[numOfDir][numOfFile].entrySet().iterator();
       long[] pointers = new long[list[numOfDir][numOfFile].size()];
       int counter = 0;
       while (it.hasNext()) {
         Map.Entry<String, String> m = (Map.Entry<String, String>) it.next();
         String key = m.getKey();
         db.write(key.getBytes("UTF-8"));
         db.write("\0".getBytes("UTF-8"));
         pointers[counter] = db.getFilePointer();
         db.seek(pointers[counter] + 4);
         ++counter;
       }
       it = list[numOfDir][numOfFile].entrySet().iterator();
       counter = 0;
       while (it.hasNext()) {
         Map.Entry<String, String> m = (Map.Entry<String, String>) it.next();
         String value = m.getValue();
         int curPointer = (int) db.getFilePointer();
         db.seek(pointers[counter]);
         db.writeInt(curPointer);
         db.seek(curPointer);
         db.write(value.getBytes("UTF-8"));
         ++counter;
       }
     } catch (Exception e) {
       db.close();
       throw new Exception(e);
     }
     db.close();
     if (dbDir.list().length == 0) {
       dbDir.delete();
     }
   } catch (Exception e) {
     throw new IllegalArgumentException();
   }
 }
Ejemplo n.º 20
0
  @Override
  public void run() {
    Database database = input.getDatabase();
    Relation<O> relation = database.getRelation(distance.getInputTypeRestriction());
    DistanceQuery<O> distanceQuery = database.getDistanceQuery(relation, distance);
    KNNQuery<O> knnQ = database.getKNNQuery(distanceQuery, DatabaseQuery.HINT_HEAVY_USE);

    // open file.
    try (RandomAccessFile file = new RandomAccessFile(out, "rw");
        FileChannel channel = file.getChannel();
        // and acquire a file write lock
        FileLock lock = channel.lock()) {
      // write magic header
      file.writeInt(KNN_CACHE_MAGIC);

      int bufsize = k * 12 * 2 + 10; // Initial size, enough for 2 kNN.
      ByteBuffer buffer = ByteBuffer.allocateDirect(bufsize);

      FiniteProgress prog =
          LOG.isVerbose() ? new FiniteProgress("Computing kNN", relation.size(), LOG) : null;

      for (DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
        final KNNList nn = knnQ.getKNNForDBID(it, k);
        final int nnsize = nn.size();

        // Grow the buffer when needed:
        if (nnsize * 12 + 10 > bufsize) {
          while (nnsize * 12 + 10 > bufsize) {
            bufsize <<= 1;
          }
          buffer = ByteBuffer.allocateDirect(bufsize);
        }

        buffer.clear();
        ByteArrayUtil.writeUnsignedVarint(buffer, it.internalGetIndex());
        ByteArrayUtil.writeUnsignedVarint(buffer, nnsize);
        int c = 0;
        for (DoubleDBIDListIter ni = nn.iter(); ni.valid(); ni.advance(), c++) {
          ByteArrayUtil.writeUnsignedVarint(buffer, ni.internalGetIndex());
          buffer.putDouble(ni.doubleValue());
        }
        if (c != nn.size()) {
          throw new AbortException("Sizes did not agree. Cache is invalid.");
        }

        buffer.flip();
        channel.write(buffer);
        LOG.incrementProcessed(prog);
      }
      LOG.ensureCompleted(prog);
      lock.release();
    } catch (IOException e) {
      LOG.exception(e);
    }
    // FIXME: close!
  }
Ejemplo n.º 21
0
  /*
   * Writes file size in WAV header (called only when recording stopped).
   */
  private void writeFileSize() {
    try {
      RandomAccessFile sizeWriter = new RandomAccessFile(filePath, "rw");
      Log.d("Microphone", "File size: " + Integer.toString(fileSize));

      sizeWriter.seek(4); // write new file size + RIFF header size
      sizeWriter.writeInt(Integer.reverseBytes(fileSize + 36));

      sizeWriter.seek(40); // write new file size
      sizeWriter.writeInt(Integer.reverseBytes(fileSize));

      sizeWriter.close();
    } catch (Exception e) {
      Log.e("Microphone", "Error writing file size.");
    }
    // HACK: tags file with modification time 0, should differentiate a file in
    // "recordings" that is in progress from one that is done but with the same
    // name
    if (subFolder.equals("recordings")) (new File(filePath)).setLastModified(0);
  }
Ejemplo n.º 22
0
  public void saveAllOpenLevels(RandomAccessFile savefile) throws IOException {
    System.out.printf("Entering map saver at %d!\n", savefile.getFilePointer());
    int mapsToSave = loadedMaps.size();
    savefile.writeInt(mapsToSave);

    saveMap(1, savefile);
    saveMap(0, savefile);
    saveMap(-1, savefile);
    saveMap(-2, savefile);
    saveMap(-100, savefile);
  }
Ejemplo n.º 23
0
  /**
   * This constructor is called by the log manager to create the file. A writer is created at the
   * same time, and its presence indicates that the file is open for writing.
   *
   * @throws IOException
   */
  public HALogFile(final IRootBlockView rbv, final IHALogManagerCallback callback)
      throws IOException {
    m_callback = callback;
    m_haLogFile = getHALogFileName(m_callback.getHALogDir(), rbv.getCommitCounter());

    if (m_haLogFile.exists())
      throw new IllegalStateException("File already exists: " + m_haLogFile.getAbsolutePath());

    final File parentDir = m_haLogFile.getParentFile();

    // Make sure the parent directory(ies) exist.
    if (!parentDir.exists())
      if (!parentDir.mkdirs()) throw new IOException("Could not create directory: " + parentDir);

    m_raf = new RandomAccessFile(m_haLogFile, "rw");
    m_channel = m_raf.getChannel();
    m_storeType = rbv.getStoreType();

    m_openRootBlock = rbv;
    m_closeRootBlock = null; // file NOT closed

    m_magic = MAGIC;
    m_version = VERSION1;

    /*
     * Write the MAGIC and version on the file.
     */
    m_raf.seek(0);
    m_raf.writeInt(m_magic);
    m_raf.writeInt(m_version);

    // Write opening rootblock as both BLOCK0 and BLOCK1
    writeRootBlock(true, rbv); // as BLOCK0
    writeRootBlock(false, rbv); // as BLOCK1

    m_writePosition = START_DATA;

    m_writer = new HALogWriter();

    if (log.isInfoEnabled()) log.info("Opening HALogFile: " + m_haLogFile.getAbsolutePath());
  }
Ejemplo n.º 24
0
  /**
   * Close the I/O stream and save any unsaved data.
   *
   * @exception IOException from library call
   */
  public void close() throws IOException {
    if (headerSize > 0) {
      // write number of rows, CRC
      outStream.seek(NUMROWS_OFFSET);
      outStream.writeLong(numRows);

      outStream.seek(headerSize - CRC_SIZE);
      outStream.writeInt(CRC);
    }

    outStream.close();
  }
Ejemplo n.º 25
0
  protected void writeCorruptedData(RandomAccessFile file) throws IOException {
    final String messageForPreUpgradeVersion =
        "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
            + "of Hadoop prior to 0.13 (which are incompatible\n"
            + "with this directory layout) will fail to start.\n";

    file.seek(0);
    file.writeInt(FSConstants.LAYOUT_VERSION);
    org.apache.hadoop.io.UTF8.writeString(file, "");
    file.writeBytes(messageForPreUpgradeVersion);
    file.getFD().sync();
  }
Ejemplo n.º 26
0
Archivo: RAF.java Proyecto: Utlesh/code
  public static void main(String args[]) {
    try {
      String fname = "d:\\q.txt";
      String mode;
      // mode = "r";//r : file must exist
      mode = "rw"; // rw : file will be created or opened

      // open the file
      RandomAccessFile raf = new RandomAccessFile(fname, mode);

      /*
      //seek and write demo

         raf.seek(10);//position file r/w pointer at index 10 wrt BOF
         //a seek beyond file size causes file to grow upto the seek value
         raf.write(65);//raf.write('A');

      */

      // r/w java datatypes
      int i1, i2;
      float f1, f2;
      char c1, c2;
      String s1, s2;

      i1 = -10;
      f1 = 1234.5678F;
      c1 = 'q';
      s1 = "hello files";

      raf.seek(0); // reach BOF
      raf.writeInt(i1);
      raf.writeFloat(f1);
      raf.writeChar(c1);
      raf.writeUTF(s1);

      raf.seek(0); // reach BOF
      i2 = raf.readInt();
      f2 = raf.readFloat();
      c2 = raf.readChar();
      s2 = raf.readUTF();

      System.out.println(i2);
      System.out.println(f2);
      System.out.println(c2);
      System.out.println(s2);

      // close the file
      raf.close();
    } catch (IOException ex) {
      System.out.println(ex); // ex converts into ex.toString()
    }
  } // main
Ejemplo n.º 27
0
  public void post(long timestamp, float value) throws IOException {
    File file = getFile();
    RandomAccessFile rdf = null;

    try {
      rdf = new RandomAccessFile(file, "rw");

      // On vérifie que la longueur est cohérente
      long len = rdf.length();
      if (len > 0) {
        int mod = (int) (len % DATA_LEN);
        if (mod != 0) {
          logger.warning(
              "Taille de fichier incoherence ("
                  + len / DATA_LEN
                  + "x"
                  + DATA_LEN
                  + ", reste "
                  + mod
                  + "). retour a "
                  + (len - mod));
          len = len - mod;
        }

        if (timestamp < getLast(rdf).timestamp) {
          logger.warning(
              "la nouvelle valeur anterieure a la derniere (prev:"
                  + sdf.format(new Date((long) last.timestamp * 1000))
                  + " new:"
                  + sdf.format(new Date((long) timestamp * 1000))
                  + ")");
        }

        // Positionnement en fin de fichier
        rdf.seek(len);
      }

      // On écrit l'enregistrement
      if (timestamp > Integer.MAX_VALUE) {
        logger.warning("timestamp tronqué : " + timestamp + "/" + (int) timestamp);
      }

      if (last == null) last = new Entry();
      last.timestamp = (int) timestamp;
      last.value = value;

      logger.fine("write: " + value + "(" + sdf.format(new Date(timestamp * 1000)) + ")");
      rdf.writeInt((int) last.timestamp);
      rdf.writeFloat(last.value);
    } finally {
      if (rdf != null) rdf.close();
    }
  }
  public static void main(String[] args) throws IOException {
    try ( // Create a random access file
    RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw"); ) {
      // Clear the file to destroy the old contents if exists
      inout.setLength(0);

      // Write new integers to the file
      for (int i = 0; i < 200; i++) inout.writeInt(i);

      // Display the current length of the file
      System.out.println("Current file length is " + inout.length());

      // Retrieve the first number
      inout.seek(0); // Move the file pointer to the beginning
      System.out.println("The first number is " + inout.readInt());

      // Retrieve the second number
      inout.seek(1 * 4); // Move the file pointer to the second number
      System.out.println("The second number is " + inout.readInt());

      // Retrieve the tenth number
      inout.seek(9 * 4); // Move the file pointer to the tenth number
      System.out.println("The tenth number is " + inout.readInt());

      // Modify the eleventh number
      inout.writeInt(555);

      // Append a new number
      inout.seek(inout.length()); // Move the file pointer to the end
      inout.writeInt(999);

      // Display the new length
      System.out.println("The new length is " + inout.length());

      // Retrieve the new eleventh number
      inout.seek(10 * 4); // Move the file pointer to the eleventh number
      System.out.println("The eleventh number is " + inout.readInt());
    }
  }
Ejemplo n.º 29
0
  private void writeNameIdEntry(NameFileIdEntry nameFileIdEntry, boolean sync) throws IOException {

    nameIdMapHolder.seek(nameIdMapHolder.length());

    final int nameSize = OStringSerializer.INSTANCE.getObjectSize(nameFileIdEntry.name);
    byte[] serializedName = new byte[nameSize];
    OStringSerializer.INSTANCE.serialize(nameFileIdEntry.name, serializedName, 0);

    nameIdMapHolder.writeInt(nameSize);
    nameIdMapHolder.write(serializedName);
    nameIdMapHolder.writeLong(nameFileIdEntry.fileId);

    if (sync) nameIdMapHolder.getFD().sync();
  }
Ejemplo n.º 30
0
  @Override
  public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out)
      throws IOException {
    Objects.requireNonNull(stream);
    Objects.requireNonNull(fileType);
    Objects.requireNonNull(out);

    // throws IllegalArgumentException if not supported
    WaveFileFormat waveFileFormat = (WaveFileFormat) getAudioFileFormat(fileType, stream);

    // first write the file without worrying about length fields
    FileOutputStream fos = new FileOutputStream(out); // throws IOException
    BufferedOutputStream bos = new BufferedOutputStream(fos, bisBufferSize);
    int bytesWritten = writeWaveFile(stream, waveFileFormat, bos);
    bos.close();

    // now, if length fields were not specified, calculate them,
    // open as a random access file, write the appropriate fields,
    // close again....
    if (waveFileFormat.getByteLength() == AudioSystem.NOT_SPECIFIED) {

      int dataLength = bytesWritten - waveFileFormat.getHeaderSize();
      int riffLength = dataLength + waveFileFormat.getHeaderSize() - 8;

      RandomAccessFile raf = new RandomAccessFile(out, "rw");
      // skip RIFF magic
      raf.skipBytes(4);
      raf.writeInt(big2little(riffLength));
      // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
      raf.skipBytes(4 + 4 + 4 + WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType()) + 4);
      raf.writeInt(big2little(dataLength));
      // that's all
      raf.close();
    }

    return bytesWritten;
  }