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);
 }
  @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;
  }
 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();
   }
 }
示例#4
0
 private void loadFromFile() throws IOException, ReflectiveOperationException {
   RandomAccessFile file = null;
   try {
     int fieldId = 0;
     file = new RandomAccessFile(filePath, "r");
     while (file.getFilePointer() < file.length()) {
       String fieldName = file.readUTF();
       int fieldType = file.readUnsignedByte();
       BitSet bitSet = BitSet.valueOf(new byte[] {file.readByte()});
       boolean indexed = bitSet.get(BIT_INDEX_INDEXED);
       boolean stored = bitSet.get(BIT_INDEX_STORED);
       Field f = new Field();
       f.setFieldId(fieldId);
       f.setFieldName(fieldName);
       f.setIsIndexed(indexed);
       f.setIsStored(stored);
       f.setFieldType(fieldTypeStore.findTypeById(fieldType));
       fieldIdMapping.add(f);
       fieldNameMapping.put(f.getFieldName(), f);
       fieldId++;
     }
   } finally {
     if (file != null) {
       file.close();
     }
   }
 }
 static void display() throws IOException {
   RandomAccessFile rf = new RandomAccessFile(file, "r");
   for (int i = 0; i < 7; i++) {
     System.out.println("Value " + i + " : " + rf.readDouble());
   }
   System.out.println(rf.readUTF());
   rf.close();
 }
  public void testEmptyList() throws IOException {
    final File file = File.createTempFile("asdf", "asdf");
    file.deleteOnExit();
    final RandomAccessFile raf = new RandomAccessFile(file, "rw");

    raf.writeUTF("Hello World!");
    final List<String> l1 = Collections.emptyList();
    RAFList.write(raf, l1, RAFSerializer.STRING);
    raf.writeUTF("Goodbye World!");

    raf.seek(0);
    assertEquals("Hello World!", raf.readUTF());
    final RAFList<String> l1Copy = RAFList.create(raf, RAFSerializer.STRING, raf.getFilePointer());
    assertEquals(l1, l1Copy);
    raf.seek(l1Copy.getEndOffset());
    assertEquals("Goodbye World!", raf.readUTF());
  }
示例#7
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 void testFileList(final RAFSerializer<String> serializer) throws IOException {
    final File file = File.createTempFile("asdf", "asdf");
    file.deleteOnExit();
    final RandomAccessFile raf = new RandomAccessFile(file, "rw");

    raf.writeUTF("Hello World!");
    final List<String> l1 = Arrays.asList("1a", "1bc", "1def");
    final List<String> l2 = Arrays.asList("2aa", "2abc", "2adef");
    RAFList.write(raf, l1, serializer);
    RAFList.write(raf, l2, serializer);
    raf.writeUTF("Goodbye World!");

    raf.seek(0);
    assertEquals("Hello World!", raf.readUTF());
    final RAFList<String> l1Copy = RAFList.create(raf, serializer, raf.getFilePointer());
    assertEquals(l1, l1Copy);
    final RAFList<String> l2Copy = RAFList.create(raf, serializer, l1Copy.getEndOffset());
    assertEquals(l2, l2Copy);
    raf.seek(l2Copy.getEndOffset());
    assertEquals("Goodbye World!", raf.readUTF());
  }
示例#9
0
  public static void main(String args[]) {
    RandomAccessFile classe = null;
    Scanner entrada = new Scanner(System.in);
    Aluno b = new Aluno();
    boolean achou = false;
    float media;

    try {
      classe = new RandomAccessFile("c:\\alunos.dat", "rw");

      achou = false;
      while (true) {
        b.numero = classe.readInt();
        b.nome = classe.readUTF();
        b.curso = classe.readUTF();
        b.nota1 = classe.readFloat();
        b.nota2 = classe.readFloat();
        media = (float) ((b.nota1 + b.nota2) / 2);
        if (media >= 7) {
          System.out.print("\nNome: " + b.nome);
          System.out.print("\nCurso: " + b.curso);
          System.out.print("\nNota1: " + b.nota1);
          System.out.print("\nNota2: " + b.nota2);
          System.out.print("\nMedia: " + media + "\n");
        }
      }
    } // fim try
    catch (EOFException e) {
      try {
        classe.close();

      } // fim try
      catch (IOException e2) {
        System.out.println("\nErro de I/O");
      }
    } // fimn catch (EOFException e)
    catch (IOException e) {
      System.out.println("Erro na criacao o arquivo");
    }
  } // fim main
示例#10
0
  /** {@inheritDoc} */
  public String readUTF() throws IOException {
    final String token;

    // peek ahead to determine the length of the String:

    final long position = dataInput.getChannel().position();
    final int stringLength = readShort();
    dataInput.seek(position);
    fileSize -= stringLength;
    if (fileSize < 0) {
      throw new EOFException();
    }

    token = dataInput.readUTF();
    return token;
  }
  public My_Room_AC_db(String name) {
    y = new ArrayList<String>();

    try {
      raf = new RandomAccessFile("ac_db.dat", "r");
      String arr2[] = name.split("#");
      while (true) {
        String rec = raf.readUTF();
        String arr[] = rec.split("#");
        if (arr[0].equals(arr2[0])) {
          y.add(name);
        } else {
          y.add(rec);
        }
      }
    } catch (Exception ep) {
    } finally {
      try {
        // if(raf!=null)
        raf.close();
        File f = new File("ac_db.dat", "r");
        f.delete();
      } catch (Exception ex) {
      }
    }

    raf = null;
    try {
      raf = new RandomAccessFile("ac_db.dat", "rw");
      for (String ss : y) {
        raf.writeUTF(ss);
      }
    } catch (Exception ef) {
    } finally {
      try {
        raf.close();
      } catch (Exception ex) {
      }
    }
  }
示例#12
0
  public T readObj(String fileName) {
    RandomAccessFile file = null;
    T retObj = null;

    if (!configDirExists(fileName)) {
      return null;
    }

    try {
      file = new RandomAccessFile(fileName, "rw");
      if (debug) {
        System.out.printf("ConfigLoader reading:%s\n", fileName);
      }
      retObj = (T) xstream.fromXML(file.readUTF());

    } catch (IOException ex) {
      System.err.printf(
          "Warning: failed to read config:%s : %s -- %s\n",
          configPathToFile, fileName, getPathToConfigDir());
      return null;
    } finally {
      try {
        if (file != null) {
          file.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    if (retObj != null && retObj instanceof ConfPortfolio) {
      ConfPortfolio config = (ConfPortfolio) retObj;
      if (config.useCurentDayAsEndingDate) {
        config.inputEndingDate = new DateTime();
      }
    }

    return retObj;
  }
 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;
 }
示例#14
0
 private String readString(long strOffset) throws IOException {
   stringFile.seek(strOffset);
   return stringFile.readUTF();
 }
示例#15
0
 /* @see java.io.DataInput.readUTF() */
 public String readUTF() throws IOException {
   raf.seek(position);
   String utf8 = raf.readUTF();
   buffer(raf.getFilePointer(), 0);
   return utf8;
 }
    private java.nio.channels.FileLock lock(FileLockManager.LockMode lockMode) throws Throwable {
      LOGGER.debug(
          "Waiting to acquire {} lock on {}.", lockMode.toString().toLowerCase(), displayName);
      long timeout = System.currentTimeMillis() + lockTimeoutMs;

      // Lock the state region, with the requested mode
      java.nio.channels.FileLock stateRegionLock = lockStateRegion(lockMode, timeout);
      if (stateRegionLock == null) {
        // Can't acquire lock, get details of owner to include in the error message
        String ownerPid = "unknown";
        String ownerOperation = "unknown";
        java.nio.channels.FileLock informationRegionLock =
            lockInformationRegion(LockMode.Shared, timeout);
        if (informationRegionLock == null) {
          LOGGER.debug("Could not lock information region for {}. Ignoring.", displayName);
        } else {
          try {
            if (lockFileAccess.length() <= INFORMATION_REGION_POS) {
              LOGGER.debug(
                  "Lock file for {} is too short to contain information region. Ignoring.",
                  displayName);
            } else {
              lockFileAccess.seek(INFORMATION_REGION_POS);
              if (lockFileAccess.readByte() != INFORMATION_REGION_PROTOCOL) {
                throw new IllegalStateException(
                    String.format(
                        "Unexpected lock protocol found in lock file '%s' for %s.",
                        lockFile, displayName));
              }
              ownerPid = lockFileAccess.readUTF();
              ownerOperation = lockFileAccess.readUTF();
            }
          } finally {
            informationRegionLock.release();
          }
        }

        throw new LockTimeoutException(
            String.format(
                "Timeout waiting to lock %s. It is currently in use by another Gradle instance.%nOwner PID: %s%nOur PID: %s%nOwner Operation: %s%nOur operation: %s%nLock file: %s",
                displayName,
                ownerPid,
                metaDataProvider.getProcessIdentifier(),
                ownerOperation,
                operationDisplayName,
                lockFile));
      }

      try {
        if (lockFileAccess.length() > 0) {
          lockFileAccess.seek(STATE_REGION_POS);
          if (lockFileAccess.readByte() != STATE_REGION_PROTOCOL) {
            throw new IllegalStateException(
                String.format(
                    "Unexpected lock protocol found in lock file '%s' for %s.",
                    lockFile, displayName));
          }
        }

        if (!stateRegionLock.isShared()) {
          // We have an exclusive lock (whether we asked for it or not).
          // Update the state region
          if (lockFileAccess.length() < STATE_REGION_SIZE) {
            // File did not exist before locking
            lockFileAccess.seek(STATE_REGION_POS);
            lockFileAccess.writeByte(STATE_REGION_PROTOCOL);
            lockFileAccess.writeBoolean(false);
          }
          // Acquire an exclusive lock on the information region and write our details there
          java.nio.channels.FileLock informationRegionLock =
              lockInformationRegion(LockMode.Exclusive, timeout);
          if (informationRegionLock == null) {
            throw new IllegalStateException(
                String.format(
                    "Timeout waiting to lock the information region for lock %s", displayName));
          }
          // check that the length of the reserved region is enough for storing our content
          try {
            lockFileAccess.seek(INFORMATION_REGION_POS);
            lockFileAccess.writeByte(INFORMATION_REGION_PROTOCOL);
            lockFileAccess.writeUTF(trimIfNecessary(metaDataProvider.getProcessIdentifier()));
            lockFileAccess.writeUTF(trimIfNecessary(operationDisplayName));
            lockFileAccess.setLength(lockFileAccess.getFilePointer());
          } finally {
            informationRegionLock.release();
          }
        }
      } catch (Throwable t) {
        stateRegionLock.release();
        throw t;
      }

      LOGGER.debug("Lock acquired.");
      return stateRegionLock;
    }
 /* @see java.io.DataInput.readUTF() */
 public String readUTF() throws IOException {
   return raf.readUTF();
 }