/**
  * Returns the uncompressed size of the file in a quick, but unreliable manner. It will not
  * report the correct size if:
  *
  * <ol>
  *   <li>The compressed size is larger than 2<sup>32</sup> bytes.
  *   <li>The file is broken or truncated.
  *   <li>The file has not been generated by a standard-conformant compressor.
  *   <li>It is a multi-volume GZIP stream.
  * </ol>
  *
  * <p>The advantage of this approach is, that it only reads the first 2 and last 4 bytes of the
  * target file. If the first 2 bytes are not the GZIP magic number, the raw length of the file
  * is returned.
  *
  * @see #isGzipStream(File)
  * @param file
  * @return the size of the uncompressed file content.
  */
 public static long getGzipStreamSize(File file) {
   if (!isGzipStream(file)) {
     return file.length();
   }
   RandomAccessFile raf = null;
   try {
     raf = new RandomAccessFile(file, "r");
     if (raf.length() <= 4) {
       raf.close();
       return file.length();
     }
     raf.seek(raf.length() - 4);
     int b4 = raf.read();
     int b3 = raf.read();
     int b2 = raf.read();
     int b1 = raf.read();
     return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
   } catch (IOException ex) {
     return file.length();
   } finally {
     if (raf != null)
       try {
         raf.close();
       } catch (IOException e) {
         // ignore
       }
   }
 }
  private static RandomAccessFile _acquireAdvisoryLock(RandomAccessFile raf, File file)
      throws IOException {

    try {

      // seek an advisory lock.
      if (acquireAdvisoryLock(file)) {

        // obtained advisory lock.
        return raf;
      }

      // someone else holds the advisory lock.
      try {
        raf.close();
      } catch (IOException t) {
        // log and ignore.
        log.error(t, t);
      }

      throw new IOException("Advisory lock exists: " + file.getAbsolutePath());

    } catch (IOException ex2) {

      log.error("Error while seeking advisory lock: file=" + file.getAbsolutePath(), ex2);

      try {
        raf.close();
      } catch (IOException t) {
        // log and ignore.
        log.error(t, t);
      }
      throw ex2;
    }
  }
示例#3
0
  public static void main(String args[]) throws Exception {
    String inputFile = "samplein.txt";
    String outputFile = "sampleout.txt";

    RandomAccessFile inf = new RandomAccessFile(inputFile, "r");
    RandomAccessFile outf = new RandomAccessFile(outputFile, "rw");
    long inputLength = new File(inputFile).length();

    FileChannel inc = inf.getChannel();
    FileChannel outc = outf.getChannel();

    MappedByteBuffer inputData = inc.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);

    Charset latin1 = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = latin1.newDecoder();
    CharsetEncoder encoder = latin1.newEncoder();

    CharBuffer cb = decoder.decode(inputData);

    // Process char data here

    ByteBuffer outputData = encoder.encode(cb);

    outc.write(outputData);

    inf.close();
    outf.close();
  }
示例#4
0
 public StorageRootFile(String dbPath, String options, int pageSize, FreeSpaceManager fsm) {
   this.fsm = fsm;
   PAGE_SIZE = pageSize;
   File file = new File(dbPath);
   if (!file.exists()) {
     throw DBLogger.newUser("DB file does not exist: " + dbPath);
   }
   try {
     raf = new RandomAccessFile(file, options);
     fc = raf.getChannel();
     try {
       // tryLock is supposed to return null, but it throws an Exception
       fileLock = fc.tryLock();
       if (fileLock == null) {
         fc.close();
         raf.close();
         throw DBLogger.newUser("This file is in use by another process: " + dbPath);
       }
     } catch (OverlappingFileLockException e) {
       fc.close();
       raf.close();
       throw DBLogger.newUser("This file is in use by another PersistenceManager: " + dbPath);
     }
     if (ZooDebug.isTesting()) {
       ZooDebug.registerFile(fc);
     }
   } catch (IOException e) {
     throw DBLogger.newFatal("Error opening database: " + dbPath, e);
   }
 }
示例#5
0
    public void memoryCopyParition() throws IOException {
      if (DEBUG_MODE) {
        mBuf.flip();
        CommonUtils.printByteBuffer(LOG, mBuf);
      }
      mBuf.flip();
      long sum = 0;
      String str = "th " + mMsg + " @ Worker ";

      if (mOneToMany) {
        ByteBuffer dst = null;
        RandomAccessFile file = null;
        if (mMemoryOnly) {
          dst = ByteBuffer.allocateDirect(FILE_BYTES);
        }
        for (int times = mLeft; times < mRight; times++) {
          long startTimeMs = System.currentTimeMillis();
          if (!mMemoryOnly) {
            file = new RandomAccessFile(FOLDER + (mWorkerId + BASE_FILE_NUMBER), "rw");
            dst = file.getChannel().map(MapMode.READ_WRITE, 0, FILE_BYTES);
          }
          dst.order(ByteOrder.nativeOrder());
          for (int k = 0; k < BLOCKS_PER_FILE; k++) {
            mBuf.array()[0] = (byte) (k + mWorkerId);
            dst.put(mBuf.array());
          }
          dst.clear();
          sum += dst.get(times);
          dst.clear();
          if (!mMemoryOnly) {
            file.close();
          }
          logPerIteration(startTimeMs, times, str, mWorkerId);
        }
      } else {
        ByteBuffer dst = null;
        RandomAccessFile file = null;
        if (mMemoryOnly) {
          dst = ByteBuffer.allocateDirect(FILE_BYTES);
        }
        for (int times = mLeft; times < mRight; times++) {
          long startTimeMs = System.currentTimeMillis();
          if (!mMemoryOnly) {
            file = new RandomAccessFile(FOLDER + (mWorkerId + BASE_FILE_NUMBER), "rw");
            dst = file.getChannel().map(MapMode.READ_WRITE, 0, FILE_BYTES);
          }
          dst.order(ByteOrder.nativeOrder());
          for (int k = 0; k < BLOCKS_PER_FILE; k++) {
            dst.get(mBuf.array());
          }
          sum += mBuf.get(times % 16);
          dst.clear();
          if (!mMemoryOnly) {
            file.close();
          }
          logPerIteration(startTimeMs, times, str, mWorkerId);
        }
      }
      Results[mWorkerId] = sum;
    }
 /**
  * reads the content of an existing file using the current domain
  *
  * @param domain The namespace used to identify the application domain (1st level directory) to
  *     use
  * @param path The path relative to the domain for the file
  * @param block The sequential block number for the data to be read starting with 1
  * @param len The length of the block in bytes
  * @return The contents of the file
  */
 public byte[] readFromFile(String path, int block, int len) {
   byte[] buffer = null;
   try {
     if (_isLocal) {
       File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path);
       if (tmpFile.isFile()) {
         RandomAccessFile in = new RandomAccessFile(tmpFile, "r");
         in.seek((block - 1) * len);
         int result = -1;
         buffer = new byte[len];
         if (in.getFilePointer() < in.length()) {
           result = in.read(buffer);
           ByteArrayOutputStream out = new ByteArrayOutputStream(result);
           out.write(buffer, 0, result);
           in.close();
           return out.toByteArray();
         } else {
           in.close();
         }
       }
     } else {
       buffer = _remote.readFromFile(_domain, path, block, len);
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return buffer;
 }
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof EchoFile) {
      EchoFile ef = (EchoFile) msg;
      int SumCountPackage = ef.getSumCountPackage();
      int countPackage = ef.getCountPackage();
      byte[] bytes = ef.getBytes();
      String md5 = ef.getFile_md5(); // 文件名

      String path = file_dir + File.separator + md5;
      File file = new File(path);
      RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
      randomAccessFile.seek(countPackage * dataLength - dataLength);
      randomAccessFile.write(bytes);
      LOGGER.debug("总包数:" + ef.getSumCountPackage());
      LOGGER.debug("收到第" + countPackage + "包");
      LOGGER.debug("本包字节数:" + bytes.length);
      countPackage = countPackage + 1;

      if (countPackage <= SumCountPackage) {
        ef.setCountPackage(countPackage);
        ctx.writeAndFlush(ef);
        randomAccessFile.close();
      } else {
        randomAccessFile.close();
        ctx.close();
      }
    }
  }
  public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException {
    Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp");
    FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile());
    FileChannel dstOutChannel = dstOut.getChannel();
    try {
      if (!Files.isDirectory(partFolder.toPath()))
        throw new IOException("Not a directory: " + partFolder);
      File[] fileList =
          FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE)
              .toArray(new File[0]);
      Arrays.sort(fileList);
      RandomAccessFile inputFile;

      inputFile = new RandomAccessFile(fileList[0], "r");
      inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel);
      inputFile.close();
      for (int i = 1; i < fileList.length; i++) {
        inputFile = new RandomAccessFile(fileList[i], "r");
        long lastPrefix = findTurtlePrefixEnd(inputFile);
        inputFile
            .getChannel()
            .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel);
        inputFile.close();
      }
    } finally {
      dstOut.close();
    }
    Files.move(
        tmpOut,
        reconstructed.toPath(),
        StandardCopyOption.ATOMIC_MOVE,
        StandardCopyOption.REPLACE_EXISTING);
    FileUtils.deleteQuietly(tmpOut.toFile());
    FileUtils.deleteQuietly(partFolder);
  }
示例#9
0
 public void shutdown() {
   try {
     mDirectoryFile.close();
     mDataFile.close();
   } catch (IOException ioe) {
     System.err.println("LineServer: error closing files");
   }
 }
示例#10
0
  /**
   * 使用切割的方式来替换给定文件中的一段数据
   *
   * @param file 给定的文件
   * @param off 要替换的一段数据的开始位置(包括)
   * @param length 要替换的一段数据的长度,大于1
   * @param newData 用来替换旧数据的新数据
   * @throws IOException
   * @throws LengthTooBigException (fileLength - (off + length)) > 31457280
   *     因为本方法采用的是先把需要替换的数据之后的数据读到内存中,然后将文件截短,最后把之前保存的数据写到文件中。因此读到内存中的数据不能太大
   */
  public static void replaceFileDataByCutWay(File file, long off, long length, byte[] newData)
      throws IOException, LengthTooBigException {

    // 获取文件长度
    long fileLength = file.length();

    // 验证数据合法性
    CheckingUtils.valiLongValue(off, 0, fileLength - 1, "off");
    CheckingUtils.valiLongValue(off + length, off + 1, fileLength, "length");
    CheckingUtils.valiObjectIsNull(newData, "newData");

    if (newData.length > 0) {
      // 计算需读到内存的数据的长度
      long keepDataLength = fileLength - (off + length);

      // 如果需要读到内存的数据长度为0
      if (keepDataLength == 0) {
        // 打开原文件
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        // 设置长度
        raf.setLength(off);

        // 将新数据写到末尾去
        raf.write(newData);

        // 关闭原文件
        raf.close();
      } else if (keepDataLength <= 31457280) {
        // 打开原文件
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        // 读取要保存的数据
        byte[] keepData = new byte[(int) keepDataLength];
        raf.seek(off + length);
        raf.read(keepData);

        // 将文件截掉合适的长度
        if (length != 0) {
          raf.setLength(fileLength - length);
        }

        // 写入新数据
        raf.seek(off);
        raf.write(newData);

        // 写入保存的数据
        raf.write(keepData);

        // 关闭原文件
        raf.close();
      } else {
        throw new LengthTooBigException(
            "Need to read the length of data of the memory more than 30720 ((fileLength - (off + length)) > 30720)");
      }
    }
  }
 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();
   }
 }
示例#12
0
 /**
  * ±£´æÓû§µÄidºÍJQºÅÂë
  *
  * @param id Óû§id
  * @param num JQºÅÂë
  * @throws IOException
  */
 public void saveIDJQ(int id, int num) throws IOException {
   RandomAccessFile raf = getFile();
   raf.writeUTF(id + ":" + num + "\n");
   raf.close();
   raf = getFile();
   raf.seek(0);
   raf.writeUTF(id + "\n");
   raf.close();
 }
示例#13
0
  public static boolean isFileLocked(File file) {
    if (!file.exists()) {
      return false;
    }

    if (file.isDirectory()) {
      return false;
    }

    if (isSymlink(file)) {
      return false;
    }

    RandomAccessFile randomAccessFile = null;
    boolean fileLocked = false;

    try {
      // Test 1 missing permissions or locked file parts. If File is not readable == locked
      randomAccessFile = new RandomAccessFile(file, "r");
      randomAccessFile.close();
    } catch (Exception e) {
      fileLocked = true;
    }

    if (!fileLocked && file.canWrite()) {
      try {
        // Test 2:Locked file parts
        randomAccessFile = new RandomAccessFile(file, "rw");

        // Test 3: Set lock and release it again
        FileLock fileLock = randomAccessFile.getChannel().tryLock();

        if (fileLock == null) {
          fileLocked = true;
        } else {
          try {
            fileLock.release();
          } catch (Exception e) {
            /* Nothing */
          }
        }
      } catch (Exception e) {
        fileLocked = true;
      }

      if (randomAccessFile != null) {
        try {
          randomAccessFile.close();
        } catch (IOException e) {
          /* Nothing */
        }
      }
    }

    return fileLocked;
  }
示例#14
0
  private void merge(SingleHit[] hits, String prefix, int chrom) throws IOException {
    String postmp = getPositionsFname(prefix, chrom) + ".tmp";
    String weightstmp = getWeightsFname(prefix, chrom) + ".tmp";
    String lastmp = getLaSFname(prefix, chrom) + ".tmp";
    RandomAccessFile positionsRAF = new RandomAccessFile(postmp, "rw");
    RandomAccessFile weightsRAF = new RandomAccessFile(weightstmp, "rw");
    RandomAccessFile lasRAF = new RandomAccessFile(lastmp, "rw");
    int newsize = getPositionsBuffer().limit() + hits.length;
    IntBP posfile =
        new IntBP(positionsRAF.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, newsize * 4));
    FloatBP weightfile =
        new FloatBP(weightsRAF.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, newsize * 4));
    IntBP lasfile =
        new IntBP(lasRAF.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, newsize * 4));

    int oldp = 0;
    int newp = 0;
    int pos = 0;
    IntBP oldpositions = getPositionsBuffer();
    FloatBP oldweights = getWeightsBuffer();
    IntBP oldlas = getLASBuffer();
    while (oldp < oldpositions.limit() || newp < hits.length) {
      while (newp < hits.length
          && (oldp == oldpositions.limit() || hits[newp].pos <= oldpositions.get(oldp))) {
        posfile.put(pos, hits[newp].pos);
        weightfile.put(pos, hits[newp].weight);
        lasfile.put(pos, Hits.makeLAS(hits[newp].length, hits[newp].strand));
        newp++;
        pos++;
      }
      while (oldp < oldpositions.limit()
          && (newp == hits.length || oldpositions.get(oldp) <= hits[newp].pos)) {
        posfile.put(pos, oldpositions.get(oldp));
        weightfile.put(pos, oldweights.get(oldp));
        lasfile.put(pos, oldlas.get(oldp));
        oldp++;
        pos++;
      }
      //            System.err.println(String.format("%d %d %d", pos, newp, oldp));
    }
    posfile = null;
    weightfile = null;
    lasfile = null;
    oldpositions = null;
    oldweights = null;
    oldlas = null;
    positionsRAF.close();
    weightsRAF.close();
    lasRAF.close();
    /* ideally this part with the renames would atomic... */
    (new File(postmp)).renameTo(new File(getPositionsFname(prefix, chrom)));
    (new File(weightstmp)).renameTo(new File(getWeightsFname(prefix, chrom)));
    (new File(lastmp)).renameTo(new File(getLaSFname(prefix, chrom)));
  }
示例#15
0
 public static void twoResourcesRandomAccessFile() throws IOException {
   RandomAccessFile a = null;
   RandomAccessFile b = null;
   try {
     a = new RandomAccessFile("", "rw");
     b = new RandomAccessFile("", "rw");
   } finally {
     if (a != null) a.close();
     if (b != null) b.close();
   }
 }
示例#16
0
  private final void testVerify(String subDir) throws Exception {
    Verifier verifier = new Verifier(testData(subDir));
    RandomAccessFile activeInput = new RandomAccessFile(testData(subDir) + "/1.out", "r");
    String activeSignature = activeInput.readLine();
    activeInput.close();
    RandomAccessFile primaryInput = new RandomAccessFile(testData(subDir) + "/2.out", "r");
    String primarySignature = primaryInput.readLine();
    primaryInput.close();

    assertTrue(verifier.verify(input, activeSignature));
    assertTrue(verifier.verify(input, primarySignature));
  }
 public synchronized void forceClose() throws IOException {
   if (cnt > 0) {
     // normal case, close exceptions propagated
     cnt = 0;
     in.close();
   } else {
     // should already be closed, ignore exception
     try {
       in.close();
     } catch (IOException ioex) {
     }
   }
 }
示例#18
0
 private final void testDecrypt(KeyczarReader reader, String subDir) throws Exception {
   Crypter crypter = new Crypter(reader);
   RandomAccessFile activeInput = new RandomAccessFile(testData(subDir) + "/1.out", "r");
   String activeCiphertext = activeInput.readLine();
   activeInput.close();
   RandomAccessFile primaryInput = new RandomAccessFile(testData(subDir) + "/2.out", "r");
   String primaryCiphertext = primaryInput.readLine();
   primaryInput.close();
   String activeDecrypted = crypter.decrypt(activeCiphertext);
   assertEquals(input, activeDecrypted);
   String primaryDecrypted = crypter.decrypt(primaryCiphertext);
   assertEquals(input, primaryDecrypted);
 }
示例#19
0
 public static void main(String[] args) throws IOException {
   RandomAccessFile rf = new RandomAccessFile(file, "rw");
   for (int i = 0; i < 7; i++) {
     rf.writeDouble(i * 1.414);
   }
   rf.writeUTF("The end of the file.");
   rf.close();
   display();
   rf = new RandomAccessFile(file, "rw");
   rf.seek(5 * 8);
   rf.writeDouble(47.0001);
   rf.close();
   display();
 }
  @FixFor("MODE-1358")
  @Test
  public void shouldCopyFilesUsingStreams() throws Exception {
    // Copy a large file into a temporary file ...
    File tempFile = File.createTempFile("copytest", "pdf");
    RandomAccessFile destinationRaf = null;
    RandomAccessFile originalRaf = null;
    try {
      URL sourceUrl = getClass().getResource("/docs/postgresql-8.4.1-US.pdf");
      assertThat(sourceUrl, is(notNullValue()));
      File sourceFile = new File(sourceUrl.toURI());
      assertThat(sourceFile.exists(), is(true));
      assertThat(sourceFile.canRead(), is(true));
      assertThat(sourceFile.isFile(), is(true));

      boolean useBufferedStream = true;
      final int bufferSize = AbstractBinaryStore.bestBufferSize(sourceFile.length());

      destinationRaf = new RandomAccessFile(tempFile, "rw");
      originalRaf = new RandomAccessFile(sourceFile, "r");

      FileChannel destinationChannel = destinationRaf.getChannel();
      OutputStream output = Channels.newOutputStream(destinationChannel);
      if (useBufferedStream) output = new BufferedOutputStream(output, bufferSize);

      // Create an input stream to the original file ...
      FileChannel originalChannel = originalRaf.getChannel();
      InputStream input = Channels.newInputStream(originalChannel);
      if (useBufferedStream) input = new BufferedInputStream(input, bufferSize);

      // Copy the content ...
      Stopwatch sw = new Stopwatch();
      sw.start();
      IoUtil.write(input, output, bufferSize);
      sw.stop();
      System.out.println(
          "Time to copy \""
              + sourceFile.getName()
              + "\" ("
              + sourceFile.length()
              + " bytes): "
              + sw.getTotalDuration());
    } finally {
      tempFile.delete();
      if (destinationRaf != null) destinationRaf.close();
      if (originalRaf != null) originalRaf.close();
    }
  }
示例#21
0
 /**
  * Sets the version for the given neostore file in {@code storeDir}.
  *
  * @param storeDir the store dir to locate the neostore file in.
  * @param version the version to set.
  * @return the previous version before writing.
  */
 public static long setVersion(String storeDir, long version) {
   RandomAccessFile file = null;
   try {
     file = new RandomAccessFile(new File(storeDir, NeoStore.DEFAULT_NAME), "rw");
     FileChannel channel = file.getChannel();
     channel.position(RECORD_SIZE * 2 + 1 /*inUse*/);
     ByteBuffer buffer = ByteBuffer.allocate(8);
     channel.read(buffer);
     buffer.flip();
     long previous = buffer.getLong();
     channel.position(RECORD_SIZE * 2 + 1 /*inUse*/);
     buffer.clear();
     buffer.putLong(version).flip();
     channel.write(buffer);
     return previous;
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     try {
       if (file != null) file.close();
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
示例#22
0
  @Override
  public void run() {

    try {
      while (shouldIRun) {
        Thread.sleep(crunchifyRunEveryNSeconds);
        long fileLength = crunchifyFile.length();
        if (fileLength > lastKnownPosition) {

          // Reading and writing file
          RandomAccessFile readWriteFileAccess = new RandomAccessFile(crunchifyFile, "rw");
          readWriteFileAccess.seek(lastKnownPosition);
          String crunchifyLine = null;
          while ((crunchifyLine = readWriteFileAccess.readLine()) != null) {
            for (Session s : AppLogView.sessions) {
              // s.getAsyncRemote().sendText(crunchifyLine);
              s.getBasicRemote().sendText(crunchifyLine);
            }
          }
          lastKnownPosition = readWriteFileAccess.getFilePointer();
          readWriteFileAccess.close();
        }
      }
    } catch (Exception e) {
      shouldIRun = false;
    }
  }
  private void getAgentIcons() {
    try {
      RandomAccessFile participantsFile =
          new RandomAccessFile(
              Simulator.inputFoldersPath + Simulator.inputFolder + "/participants.csv", "r");
      participantsFile.readLine();

      String currentLine = participantsFile.readLine();

      // Set the System Data
      while (!(currentLine == null)) {
        String[] theArgs = StringParseTools.readTokens(currentLine, ",");

        if (theArgs[2].contains("<player>")) {
          try {
            agentIcons.put(theArgs[1], convert(ImageIO.read(new File("images/" + theArgs[3]))));
          } catch (Exception e) {
            logger.warn(
                "Couldn't find the icon file 'images/"
                    + theArgs[3]
                    + "' for agent '"
                    + theArgs[1]
                    + "'.");
          }
        }

        // get next line
        currentLine = participantsFile.readLine();
      }
      participantsFile.close();
    } catch (Exception e) {
      logger.fatal("Error access System I/O file: ", e);
    }
  }
示例#24
0
 public void close() {
   try {
     raf.close();
   } catch (IOException ioe) {
     System.err.println(ioe);
   }
 }
示例#25
0
  private void unlock() {
    if (lock != null) {
      try {
        lock.release();
      } catch (IOException e) {
        log.error("Error releasing lock", e);
      }
    }
    if (lock_fc != null) {
      try {
        lock_fc.close();
      } catch (IOException e) {
        log.error("Error closing file channel", e);
      }
    }
    if (lock_raf != null) {
      try {
        lock_raf.close();
      } catch (IOException e) {
        log.error("Error closing file", e);
      }
    }

    lock = null;
    lock_raf = null;
    lock_fc = null;
  }
示例#26
0
  /**
   * @param filePath
   * @param seek
   * @param length
   * @return
   */
  public static byte[] readFlieToByte(String filePath, int seek, int length) {
    if (TextUtils.isEmpty(filePath)) {
      return null;
    }
    File file = new File(filePath);
    if (!file.exists()) {
      return null;
    }
    if (length == -1) {
      length = (int) file.length();
    }

    try {
      RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
      byte[] bs = new byte[length];
      randomAccessFile.seek(seek);
      randomAccessFile.readFully(bs);
      randomAccessFile.close();
      return bs;
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e(
          LogUtil.getLogUtilsTag(FileUtils.class), "readFromFile : errMsg = " + e.getMessage());
      return null;
    }
  }
示例#27
0
  /*
   * (non-Javadoc)
   * @see org.oscim.map.reader.IMapDatabase#closeFile()
   */
  @Override
  public void close() {
    instances--;
    if (instances > 0) {
      mReadBuffer = null;
      return;
    }

    try {
      sMapFileHeader = null;

      if (sDatabaseIndexCache != null) {
        sDatabaseIndexCache.destroy();
        sDatabaseIndexCache = null;
      }

      if (mInputFile != null) {
        mInputFile.close();
        mInputFile = null;
      }

      mReadBuffer = null;
    } catch (IOException e) {
      LOG.log(Level.SEVERE, null, e);
    }
  }
示例#28
0
 private static long getRecord(String storeDir, long recordPosition) {
   RandomAccessFile file = null;
   try {
     file = new RandomAccessFile(new File(storeDir), "rw");
     FileChannel channel = file.getChannel();
     /*
      * We have to check size, because the store version
      * field was introduced with 1.5, so if there is a non-clean
      * shutdown we may have a buffer underflow.
      */
     if (recordPosition > 3 && channel.size() < RECORD_SIZE * 5) {
       return -1;
     }
     channel.position(RECORD_SIZE * recordPosition + 1 /*inUse*/);
     ByteBuffer buffer = ByteBuffer.allocate(8);
     channel.read(buffer);
     buffer.flip();
     long previous = buffer.getLong();
     return previous;
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     try {
       if (file != null) file.close();
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
示例#29
0
文件: GIDE.java 项目: rexut/jkcemu
 private void execFormatTrackTask() {
   File file = this.ioFile;
   long pos = this.ioFilePos;
   int cnt = this.ioByteCnt;
   if ((file != null) && (pos >= 0) && (cnt > 0)) {
     boolean err = false;
     RandomAccessFile raf = null;
     try {
       raf = new RandomAccessFile(file, "rw");
       raf.seek(pos);
       while (cnt > 0) {
         raf.write(0);
         --cnt;
       }
       raf.close();
       raf = null;
     } catch (IOException ex) {
       err = true;
       if (!this.writeErrShown) {
         this.writeErrShown = true;
         EmuUtil.fireShowError(this.owner, null, ex);
       }
     } finally {
       EmuUtil.doClose(raf);
     }
     if (err) {
       this.errorReg = ERROR_UNCORRECTABLE_DATA;
       this.statusReg |= STATUS_ERROR;
     }
     fireInterrupt();
   }
 }
示例#30
0
 private String readInstallationFileBad(File installation) throws IOException {
   RandomAccessFile f = new RandomAccessFile(installation, "r");
   byte[] bytes = new byte[(int) f.length()];
   f.readFully(bytes);
   f.close();
   return new String(bytes);
 }