예제 #1
0
파일: Page.java 프로젝트: code4/ProjectPika
 public void loadMetaData() throws IOException {
   pageFile.seek(offset);
   nextPageId = pageFile.readInt();
   currentFill = pageFile.readInt();
   bloomfilter = pageFile.readInt();
   type = pageFile.readByte();
 }
예제 #2
0
 private Part read() throws IOException {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < PNUMLEN; i++) sb.append(raf.readChar());
   String partnum = sb.toString().trim();
   sb.setLength(0);
   for (int i = 0; i < DESCLEN; i++) sb.append(raf.readChar());
   String partdesc = sb.toString().trim();
   int qty = raf.readInt();
   int ucost = raf.readInt();
   return new Part(partnum, partdesc, qty, ucost);
 }
예제 #3
0
  public static void loadAllOpenLevels(Player player, RandomAccessFile loadfile)
      throws IOException {
    System.out.printf("Entering map loader at %d!\n", loadfile.getFilePointer());
    int mapsToLoad = loadfile.readInt();

    for (int x = 0; x < mapsToLoad; x++) {
      System.out.printf("Loading a map at %d!\n", loadfile.getFilePointer());
      int layer = loadfile.readInt();
      System.out.printf("Looks like it's map %d!\n", layer);
      loadMap(layer, player, loadfile);
    }
  }
예제 #4
0
  private boolean readIndex() {
    if (triedToReadIndex || !usePreindexedCache) {
      return false;
    }

    boolean ret = false;
    synchronized (this) {
      triedToReadIndex = true;
      RandomAccessFile raf = null;
      try {
        File indexFileName = getIndexFile();
        raf = new RandomAccessFile(indexFileName, "r");

        long fileStamp = raf.readLong();
        if (zipFile.lastModified() != fileStamp) {
          ret = false;
        } else {
          directories = new LinkedHashMap<RelativeDirectory, DirectoryEntry>();
          int numDirs = raf.readInt();
          for (int nDirs = 0; nDirs < numDirs; nDirs++) {
            int dirNameBytesLen = raf.readInt();
            byte[] dirNameBytes = new byte[dirNameBytesLen];
            raf.read(dirNameBytes);

            RelativeDirectory dirNameStr = getRelativeDirectory(new String(dirNameBytes, "UTF-8"));
            DirectoryEntry de = new DirectoryEntry(dirNameStr, this);
            de.numEntries = raf.readInt();
            de.writtenOffsetOffset = raf.readLong();
            directories.put(dirNameStr, de);
          }
          ret = true;
          zipFileLastModified = fileStamp;
        }
      } catch (Throwable t) {
        // Do nothing
      } finally {
        if (raf != null) {
          try {
            raf.close();
          } catch (Throwable tt) {
            // Do nothing
          }
        }
      }
      if (ret == true) {
        readFromIndex = true;
      }
    }

    return ret;
  }
 public IndexEntry(final Index index, final RandomAccessFile raf) throws IOException {
   this.index = index;
   token = raf.readUTF();
   startRow = raf.readInt();
   numRows = raf.readInt();
   final boolean hasNormalizedForm = raf.readBoolean();
   normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
   if (index.dict.dictFileVersion >= 6) {
     this.htmlEntries =
         CachingList.create(
             RAFList.create(raf, index.dict.htmlEntryIndexSerializer, raf.getFilePointer()), 1);
   } else {
     this.htmlEntries = Collections.emptyList();
   }
 }
예제 #6
0
 Header(final RandomAccessFile raf) throws IOException {
   byte[] bType = new byte[4];
   raf.readFully(bType);
   this.type = new String(bType, Charsets.US_ASCII);
   if (!TYPE.equals(this.type)) {
     throw new IOException("Invalid File Type " + this.type);
   }
   this.version = raf.readInt();
   int metaDataSize = raf.readInt();
   if (metaDataSize > 0) {
     this.metaData = new byte[metaDataSize];
     raf.readFully(this.metaData);
   } else {
     this.metaData = new byte[] {};
   }
 }
예제 #7
0
  /**
   * Parses the zip64 end of central directory record locator. The locator must be placed
   * immediately before the end of central directory (eocd) record starting at {@code eocdOffset}.
   *
   * <p>The position of the file cursor for {@code raf} after a call to this method is undefined an
   * callers must reposition it after each call to this method.
   */
  public static long parseZip64EocdRecordLocator(RandomAccessFile raf, long eocdOffset)
      throws IOException {
    // The spec stays curiously silent about whether a zip file with an EOCD record,
    // a zip64 locator and a zip64 eocd record is considered "empty". In our implementation,
    // we parse all records and read the counts from them instead of drawing any size or
    // layout based information.
    if (eocdOffset > ZIP64_LOCATOR_SIZE) {
      raf.seek(eocdOffset - ZIP64_LOCATOR_SIZE);
      if (Integer.reverseBytes(raf.readInt()) == ZIP64_LOCATOR_SIGNATURE) {
        byte[] zip64EocdLocator = new byte[ZIP64_LOCATOR_SIZE - 4];
        raf.readFully(zip64EocdLocator);
        ByteBuffer buf = ByteBuffer.wrap(zip64EocdLocator).order(ByteOrder.LITTLE_ENDIAN);

        final int diskWithCentralDir = buf.getInt();
        final long zip64EocdRecordOffset = buf.getLong();
        final int numDisks = buf.getInt();

        if (numDisks != 1 || diskWithCentralDir != 0) {
          throw new ZipException("Spanned archives not supported");
        }

        return zip64EocdRecordOffset;
      }
    }

    return -1;
  }
예제 #8
0
    public boolean hasNext() {
      if (raf == null || !raf.getChannel().isOpen()) return false;

      if (flagNext == true) return true; // Déjà lue

      flagNext = true;
      try {
        next = new Entry();
        next.timestamp = (long) raf.readInt();
        next.value = raf.readFloat();
        if (this.end != null && next.timestamp > this.end) {
          next = null;
          close();
          return false;
        }
        return true;
      } catch (IOException e) {
        // EOF ou autre erreur d'IO
        if (!(e instanceof EOFException)) logger.log(Level.WARNING, e.getMessage(), e);
        next = null;
        try {
          close();
        } catch (IOException e1) {
          logger.log(Level.WARNING, e.getMessage(), e);
        }
        return false;
      }
    }
 public Index(final Dictionary dict, final RandomAccessFile raf) throws IOException {
   this.dict = dict;
   shortName = raf.readUTF();
   longName = raf.readUTF();
   final String languageCode = raf.readUTF();
   sortLanguage = Language.lookup(languageCode);
   normalizerRules = raf.readUTF();
   swapPairEntries = raf.readBoolean();
   if (sortLanguage == null) {
     throw new IOException("Unsupported language: " + languageCode);
   }
   if (dict.dictFileVersion >= 2) {
     mainTokenCount = raf.readInt();
   }
   sortedIndexEntries =
       CachingList.create(
           RAFList.create(raf, indexEntrySerializer, raf.getFilePointer()), CACHE_SIZE);
   if (dict.dictFileVersion >= 4) {
     stoplist = new SerializableSerializer<Set<String>>().read(raf);
   } else {
     stoplist = Collections.emptySet();
   }
   rows =
       CachingList.create(
           UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
           CACHE_SIZE);
 }
예제 #10
0
  public List<Entry> getLastPoints(int nb) throws IOException {
    File file = getFile();
    RandomAccessFile raf = null;
    List<Entry> result = null;

    try {
      raf = new RandomAccessFile(file, "r");
      long pos = raf.length() - (nb * DATA_LEN);
      if (pos < 0) {
        nb = nb + (int) (pos / DATA_LEN);
        pos = 0;
      }
      raf.seek(pos);

      result = new ArrayList<Entry>(nb);
      Entry next = null;
      for (int i = 0; i < nb; i++) {
        next = new Entry();
        next.timestamp = (long) raf.readInt();
        next.value = raf.readFloat();
        result.add(0, next);
      }
    } finally {
      if (raf != null) raf.close();
    }
    return result;
  }
예제 #11
0
  /*
   * Creates new file in appropriate subFolder of respeakerApp.
   * Returns true if file didn't exist before.
   */
  private boolean setNewFileName(String filename) {
    File dir = new File(TabConstants.PREFIX + subFolder);
    dir.mkdirs();
    // moving file out of inProgress folder if done respeaking
    if (subFolder.equals("respeakings")) {
      new File(filePath).renameTo(new File(dir, filename));
      return true;
    }
    // otherwise create file object to check if it exists
    File outputFile = new File(dir, filename);
    try {
      if (!outputFile.exists()) {
        outputFile.createNewFile();
        filePath = outputFile.getAbsolutePath();
        fileSize = 0;
        return true;
      }
    } catch (IOException e) {
      Log.e("Microphone", "Error creating new file.");
    }

    filePath = outputFile.getAbsolutePath();

    // if recording wasn't completed (i.e. respeaking was paused halfway), gets previous fileSize
    try {
      RandomAccessFile sizeWriter = new RandomAccessFile(outputFile, "rw");
      sizeWriter.seek(40); // where size of raw data is located
      if (fileSize == 0) fileSize = Integer.reverseBytes(sizeWriter.readInt());
      sizeWriter.close();
      Log.d("Microphone", "Filesize: " + Integer.toString(fileSize));
    } catch (Exception e) {
      Log.e("Microphone", "Error reading file size");
    }
    return false;
  }
예제 #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;
  }
  @Override
  public ITmfEvent parseEvent(final ITmfContext context) {

    if (!(fEventStream instanceof TmfTraceStub)) {
      return null;
    }

    // Highly inefficient...
    final RandomAccessFile stream = ((TmfTraceStub) fEventStream).getStream();
    if (stream == null) {
      return null;
    }

    //           String name = eventStream.getName();
    //           name = name.substring(name.lastIndexOf('/') + 1);

    // no need to use synchronized since it's already cover by the calling method

    long location = 0;
    if (context != null && context.getLocation() != null) {
      location = (Long) context.getLocation().getLocationInfo();
      try {
        stream.seek(location);

        final long ts = stream.readLong();
        stream.readUTF(); /* Previously source, now unused */
        final String type = stream.readUTF();
        stream.readInt(); /* Previously reference, now unused */
        final int typeIndex = Integer.parseInt(type.substring(typePrefix.length()));
        final String[] fields = new String[typeIndex];
        for (int i = 0; i < typeIndex; i++) {
          fields[i] = stream.readUTF();
        }

        final StringBuffer content = new StringBuffer("[");
        if (typeIndex > 0) {
          content.append(fields[0]);
        }
        for (int i = 1; i < typeIndex; i++) {
          content.append(", ").append(fields[i]);
        }
        content.append("]");

        final TmfEventField root =
            new TmfEventField(ITmfEventField.ROOT_FIELD_ID, content.toString(), null);
        final ITmfEvent event =
            new TmfEvent(
                fEventStream,
                ITmfContext.UNKNOWN_RANK,
                fEventStream.createTimestamp(ts * 1000000L),
                fTypes[typeIndex],
                root);
        return event;
      } catch (final EOFException e) {
      } catch (final IOException e) {
      }
    }
    return null;
  }
예제 #14
0
  /** {@inheritDoc} */
  public int readInt() throws IOException {

    fileSize -= 4;
    if (fileSize < 0) {
      throw new EOFException();
    }
    return dataInput.readInt();
  }
 private static void alterLastIFDOffset(RandomAccessFile rFile, int fileLen) throws IOException {
   rFile.seek(0);
   rFile.skipBytes(4);
   int offsetIFD = rFile.readInt();
   while (true) {
     rFile.seek(offsetIFD);
     int dirs = rFile.readShort();
     rFile.skipBytes(dirs * 12);
     offsetIFD = rFile.readInt();
     if (offsetIFD == 0) {
       int pointer = (int) rFile.getFilePointer();
       rFile.seek(pointer - 4);
       rFile.writeInt(fileLen);
       break;
     }
   }
 }
예제 #16
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);
  }
예제 #17
0
  public void read() throws Exception {
    file.seek(0);

    System.out.print("[ ");

    while (file.getFilePointer() < file.length()) System.out.print(file.readInt() + " ");

    System.out.println("]");
  }
예제 #18
0
파일: SHeader.java 프로젝트: irlm/TinyReef
  SHeader(RandomAccessFile randomAccessFile) throws IOException {

    this.nameidx = randomAccessFile.readInt();
    this.type = randomAccessFile.readInt();
    this.flags = randomAccessFile.readInt();
    this.addr = randomAccessFile.readInt();
    this.offset = randomAccessFile.readInt();
    this.size = randomAccessFile.readInt();
    this.link = randomAccessFile.readInt();
    this.info = randomAccessFile.readInt();
    this.addralign = randomAccessFile.readInt();
    this.entsize = randomAccessFile.readInt();

    this.elfInputStream = new ELFInputStream(randomAccessFile, offset, size);
  }
예제 #19
0
  private void loadDataXM(RandomAccessFile fp) throws IOException {
    byte[] b = new byte[20];

    // WHY THE HELL AM I DOING THIS
    name = Util.readStringNoNul(fp, b, 20);
    System.out.printf("name: \"%s\"\n", name);
    fp.read(); // skip 0x1A byte

    // THIS CAN'T BE HAPPENING
    fp.read(b, 0, 20); // skip tracker name

    // OH HELL NO
    int xmver = 0xFFFF & (int) Short.reverseBytes(fp.readShort());
    System.out.printf("XM version: %04X\n", xmver);

    // WHAT IS THIS CRAP
    InhibitedFileBlock ifb = new InhibitedFileBlock(fp, Integer.reverseBytes(fp.readInt()) - 4);

    // HELP ME PLEASE
    int ordnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int respos =
        0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // can't be bothered right now --GM
    int chnnum =
        0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // yeah sure, allow out of range values
    if (chnnum > 64)
      throw new RuntimeException(
          String.format("%d-channel modules not supported (max 64)", chnnum));
    int patnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int insnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmflags = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmspeed = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmtempo = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());

    // OH PLEASE, STOP IT
    if (ordnum > 255) ordnum = 255;
    if (xmtempo > 255) xmtempo = 255;
    if (xmspeed > 255) xmspeed = 255;
    this.bpm = xmtempo;
    this.spd = xmspeed;
    this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_INSMODE | FLAG_STEREO | FLAG_VOL0MIX;

    if ((xmflags & 0x01) != 0) this.flags |= FLAG_LINEAR;

    // NONONONONONO
    System.out.printf("chn=%d ordnum=%d tempo=%d speed=%s\n", chnnum, ordnum, xmtempo, xmspeed);
    for (int i = 0; i < 256; i++) orderlist[i] = ifb.read();
    for (int i = ordnum; i < 256; i++) orderlist[i] = 255;

    ifb.done();

    // SAVE ME PLEEEEEAAASSSSEEEE
    for (int i = 0; i < patnum; i++)
      map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_XM, chnnum));
    for (int i = 0; i < insnum; i++)
      map_ins.put((Integer) (i + 1), new SessionInstrument(fp, SessionInstrument.FORMAT_XM, this));
  }
예제 #20
0
 public final int readInt() throws IOException {
   int i = mRaf.readInt();
   if (mIsLittleEndian) {
     return ((i & 0x000000ff) << 24)
         | ((i & 0x0000ff00) << 8)
         | ((i & 0x00ff0000) >>> 8)
         | ((i & 0xff000000) >>> 24);
   }
   return i;
 }
예제 #21
0
  /*
   * gets an (uncompressed) stream representing the chunk data returns null if
   * the chunk is not found or an error occurs
   */
  public synchronized DataInputStream getChunkDataInputStream(int x, int z) {
    if (outOfBounds(x, z)) {
      debugln("READ", x, z, "out of bounds");
      return null;
    }

    try {
      int offset = getOffset(x, z);
      if (offset == 0) {
        // debugln("READ", x, z, "miss");
        return null;
      }

      int sectorNumber = offset >> 8;
      int numSectors = offset & 0xFF;

      if (sectorNumber + numSectors > sectorFree.size()) {
        debugln("READ", x, z, "invalid sector");
        return null;
      }

      file.seek(sectorNumber * SECTOR_BYTES);
      int length = file.readInt();

      if (length > SECTOR_BYTES * numSectors) {
        debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors);
        return null;
      }

      byte version = file.readByte();
      if (version == VERSION_GZIP) {
        byte[] data = new byte[length - 1];
        file.read(data);
        DataInputStream ret =
            new DataInputStream(
                new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data))));
        // debug("READ", x, z, " = found");
        return ret;
      } else if (version == VERSION_DEFLATE) {
        byte[] data = new byte[length - 1];
        file.read(data);
        DataInputStream ret =
            new DataInputStream(
                new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))));
        // debug("READ", x, z, " = found");
        return ret;
      }

      debugln("READ", x, z, "unknown version " + version);
      return null;
    } catch (IOException e) {
      debugln("READ", x, z, "exception");
      return null;
    }
  }
예제 #22
0
  public static ZipFile.EocdRecord parseZip64EocdRecord(
      RandomAccessFile raf, long eocdRecordOffset, int commentLength) throws IOException {
    raf.seek(eocdRecordOffset);
    final int signature = Integer.reverseBytes(raf.readInt());
    if (signature != ZIP64_EOCD_RECORD_SIGNATURE) {
      throw new ZipException(
          "Invalid zip64 eocd record offset, sig="
              + Integer.toHexString(signature)
              + " offset="
              + eocdRecordOffset);
    }

    // The zip64 eocd record specifies its own size as an 8 byte integral type. It is variable
    // length because of the "zip64 extensible data sector" but that field is reserved for
    // pkware's proprietary use. We therefore disregard it altogether and treat the end of
    // central directory structure as fixed length.
    //
    // We also skip "version made by" (2 bytes) and "version needed to extract" (2 bytes)
    // fields. We perform additional validation at the ZipEntry level, where applicable.
    //
    // That's a total of 12 bytes to skip
    raf.skipBytes(12);

    byte[] zip64Eocd = new byte[ZIP64_EOCD_RECORD_EFFECTIVE_SIZE];
    raf.readFully(zip64Eocd);

    ByteBuffer buf = ByteBuffer.wrap(zip64Eocd).order(ByteOrder.LITTLE_ENDIAN);
    try {
      int diskNumber = buf.getInt();
      int diskWithCentralDirStart = buf.getInt();
      long numEntries = buf.getLong();
      long totalNumEntries = buf.getLong();
      buf.getLong(); // Ignore the size of the central directory
      long centralDirOffset = buf.getLong();

      if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDirStart != 0) {
        throw new ZipException(
            "Spanned archives not supported :"
                + " numEntries="
                + numEntries
                + ", totalNumEntries="
                + totalNumEntries
                + ", diskNumber="
                + diskNumber
                + ", diskWithCentralDirStart="
                + diskWithCentralDirStart);
      }

      return new ZipFile.EocdRecord(numEntries, centralDirOffset, commentLength);
    } catch (BufferUnderflowException bue) {
      ZipException zipException = new ZipException("Error parsing zip64 eocd record.");
      zipException.initCause(bue);
      throw zipException;
    }
  }
예제 #23
0
  private String readFromDataBase(final RandomAccessFile dbFile) throws MapExcept {

    try {
      int wordlen = dbFile.readInt();
      byte[] word = new byte[wordlen];
      dbFile.read(word, 0, wordlen);
      return new String(word);
    } catch (IOException e) {
      throw new MapExcept("Can't read from database");
    }
  }
예제 #24
0
파일: RAF.java 프로젝트: 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
  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());
    }
  }
  public RecordRange seek(String pattern, int size) {
    RandomAccessFile currentFile = file[size - 1];
    long pos, mid, head, tail;
    short strLen;
    byte buf[] = new byte[strSize];

    try {
      head = 0;
      tail = currentFile.length() / recLen - 1;

      while (head <= tail) {
        mid = (head + tail) / 2;
        pos = mid * recLen;
        currentFile.seek(pos);
        strLen = currentFile.readShort();
        currentFile.read(buf, 0, strLen);
        String str = new String(buf, 0, strLen);

        int cmp = pattern.compareTo(str);

        if (cmp < 0) tail = mid - 1;
        else if (cmp > 0) head = mid + 1;
        else {
          currentFile.seek(pos + lenSize + strSize);
          int spageID = currentFile.readInt();
          int soffset = currentFile.readInt();
          int epageID = currentFile.readInt();
          int eoffset = currentFile.readInt();

          return new RecordRange(new RID(spageID, soffset), new RID(epageID, eoffset));
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
예제 #27
0
  private void update() throws DatabaseCorruptedException, IOException {
    try (RandomAccessFile file = new RandomAccessFile(filePath.toString(), "r")) {
      if (file.length() == 0) {
        throw new DatabaseCorruptedException("Data base corrupted: empty file found");
      }
      List<String> keys = new LinkedList<>();
      List<Integer> offsets = new LinkedList<>();
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
      byte b;
      int counter = 0;
      do { // Read keys.
        while ((b = file.readByte()) != 0) {
          counter++;
          bytes.write(b);
        }
        ++counter;
        offsets.add(file.readInt());
        counter += 4;
        String key = bytes.toString(TableManager.CODE_FORMAT);
        bytes.reset();
        if (!checkKey(key)) {
          throw new DatabaseCorruptedException("Wrong key found in file " + filePath.toString());
        }
        keys.add(key);
      } while (counter < offsets.get(0));

      offsets.add((int) file.length());
      offsets.remove(0); // It's current position in file, we don't need it in list.
      Iterator<String> keyIterator = keys.iterator();
      for (int nextOffset : offsets) { // Read values.
        while (counter < nextOffset) {
          bytes.write(file.readByte());
          counter++;
        }
        if (bytes.size() > 0) {
          try {
            fileMap.put(
                keyIterator.next(),
                provider.deserialize(table, bytes.toString(TableManager.CODE_FORMAT)));
          } catch (ParseException e) {
            throw new RuntimeException(
                "Data corrupted in file " + filePath.toString() + " : " + e.getMessage());
          }
          bytes.reset();
        } else {
          throw new DatabaseCorruptedException("Data corrupted in file " + filePath.toString());
        }
      }
      bytes.close();
    }
  }
예제 #28
0
  /* Package visible for testing */
  static CentralDirectory findCentralDirectory(RandomAccessFile raf)
      throws IOException, ZipException {
    long scanOffset = raf.length() - ENDHDR;
    if (scanOffset < 0) {
      throw new ZipException("File too short to be a zip file: " + raf.length());
    }

    long stopOffset = scanOffset - 0x10000 /* ".ZIP file comment"'s max length */;
    if (stopOffset < 0) {
      stopOffset = 0;
    }

    int endSig = Integer.reverseBytes(ENDSIG);
    while (true) {
      raf.seek(scanOffset);
      if (raf.readInt() == endSig) {
        break;
      }

      scanOffset--;
      if (scanOffset < stopOffset) {
        throw new ZipException("End Of Central Directory signature not found");
      }
    }
    // Read the End Of Central Directory. ENDHDR includes the signature
    // bytes,
    // which we've already read.

    // Pull out the information we need.
    raf.skipBytes(2); // diskNumber
    raf.skipBytes(2); // diskWithCentralDir
    raf.skipBytes(2); // numEntries
    raf.skipBytes(2); // totalNumEntries
    CentralDirectory dir = new CentralDirectory();
    dir.size = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    dir.offset = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;
    return dir;
  }
예제 #29
0
 protected long readHeader(RandomAccessFile raFile) throws IOException {
   raFile.seek(0);
   if (raFile.length() == 0) return -1;
   String versionHint = raFile.readUTF();
   if (!"GH".equals(versionHint))
     throw new IllegalArgumentException(
         "Not a GraphHopper file! Expected 'GH' as file marker but was " + versionHint);
   // use a separate version field
   int majorVersion = raFile.readInt();
   if (majorVersion != version())
     throw new IllegalArgumentException(
         "This GraphHopper file has the wrong version! "
             + "Expected "
             + version()
             + " but was "
             + majorVersion);
   long bytes = raFile.readLong();
   segmentSize(raFile.readInt());
   for (int i = 0; i < header.length; i++) {
     header[i] = raFile.readInt();
   }
   return bytes;
 }
예제 #30
0
  private NameFileIdEntry readNextNameIdEntry() throws IOException {
    try {
      final int nameSize = nameIdMapHolder.readInt();
      byte[] serializedName = new byte[nameSize];

      nameIdMapHolder.readFully(serializedName);

      final String name = OStringSerializer.INSTANCE.deserialize(serializedName, 0);
      final long fileId = nameIdMapHolder.readLong();

      return new NameFileIdEntry(name, fileId);
    } catch (EOFException eof) {
      return null;
    }
  }