Beispiel #1
0
  @SuppressWarnings({"unchecked"})
  void initializeFS() {
    try {
      JSONObject obj = new JSONObject();
      JSONArray jar = new JSONArray();
      jar.add("0 1#1");
      obj.put("version", jar);
      obj.put("lastblock", "1");
      version = 0;
      file.write(obj.toJSONString().getBytes());

      superBlock = new SuperBlock(obj.toJSONString().getBytes());
      // Done super block
      lastblock = 1;
      file.seek(1024);
      // root direc
      JSONObject obj1 = new JSONObject();
      JSONArray ch_dir = new JSONArray();
      obj1.put("dir", ch_dir);
      file.write(obj1.toJSONString().getBytes());
      file.close();

      getFile();
      superBlock.loadDMap(version, file);

    } catch (IOException | ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Persists the bloom filter to disk.
   *
   * @throws IOException if I/O errors are encountered.
   */
  public void flush() throws IOException {
    cacheLock.writeLock().lock();
    try {
      checkIfOpen();
      if (cacheDirty && unflushedChanges != null && file != null) {
        final int offset = this.metadata.getHeaderLength();

        // it's actually a disk-backed filter with changes
        if (unflushedChangeCounter.get() >= seekThreshold) {
          file.seek(offset);
          file.write(cache); // can probably be made more efficient
          file.getFD().sync();
        } else {
          for (Map.Entry<Integer, Byte> change : unflushedChanges.entrySet()) {
            file.seek(change.getKey() + offset);
            file.write(change.getValue());
          }
        }
        cacheDirty = false;
        unflushedChanges.clear();
        unflushedChangeCounter.set(0);
      }
    } finally {
      cacheLock.writeLock().unlock();
    }
  }
Beispiel #3
0
  private void writeBlock(String path, int id, byte data[]) throws IOException {
    int writer_id = (id / FILE_BLK_SIZE);
    int writer_blk_id = (id % FILE_BLK_SIZE);

    // Backfill the writer array
    if (writer_id >= fFileRWList.size()) {
      // Add a new database file
      File f = new File(fDBDir, (writer_id + 1) + ".db");
      RandomAccessFile rw = new RandomAccessFile(f, "rw");
      fFileRWList.add(rw);
      fLastRwBlkLen = 0;
    }

    RandomAccessFile rw = fFileRWList.get(writer_id);

    // See if the file is long enough
    if (writer_blk_id >= fLastRwBlkLen) {
      byte tmp[] = new byte[BLK_SIZE];

      // Extend the length
      rw.seek(fLastRwBlkLen * BLK_SIZE);
      while (writer_blk_id >= fLastRwBlkLen) {
        rw.write(tmp);
        fLastRwBlkLen++;
      }
    }

    // Finally, seek to the block offset and write the block
    rw.seek(writer_blk_id * BLK_SIZE);
    rw.write(data);
  }
  /**
   * appends image to given tiff file
   *
   * <p>if file is empty then this method write image to the file otherwise it will append the image
   * after previous image. <strong>Please note: This method supports only Big endian tiff
   * files</strong>
   *
   * @param img BufferedImage to append image
   * @param fileName The name of the file where the image will be written
   * @throws IOException if the file is unreadable
   */
  public void append(BufferedImage img, String fileName) throws IOException {
    File file = new File(fileName);
    if (file.exists() && file.length() > 0) {
      int endFile = (int) file.length();
      int padding = endFile % 8;
      RandomAccessFile rFile = new RandomAccessFile(fileName, "rw");
      rFile.seek(endFile);
      for (int i = 0; i < padding; i++) {
        rFile.write(0);
      }
      endFile += padding;
      alterLastIFDOffset(rFile, endFile);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] data = getComponentBytes(img);
      boolean hasAlpha = data.length > (img.getWidth() * img.getHeight() * 3);
      if (compress) {
        data = performCompression(data, img.getWidth(), img.getHeight(), hasAlpha);
      }
      writeContents(bos, data, img.getWidth(), img.getHeight(), endFile, hasAlpha, compress);
      bos.close();
      data = bos.toByteArray();
      rFile.seek(endFile);
      rFile.write(data);
      rFile.close();

    } else {
      BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
      createImage(img, out, compress);
      out.close();
    }
  }
 public void save(boolean clock, int crc, byte[] buf, int offset, int length) throws IOException {
   checkClosed();
   if (size <= saved) {
     return;
   }
   length = (int) Math.min(length, size - saved);
   if (null == file) {
     file = new RandomAccessFile(partialFile, "rw");
   }
   file.seek(saved);
   file.write(buf, offset, length);
   scratch[0] = (byte) (clock ? 1 : 0);
   scratch[1] = (byte) ((crc >> 24) & 0xff);
   scratch[2] = (byte) ((crc >> 16) & 0xff);
   scratch[3] = (byte) ((crc >> 8) & 0xff);
   scratch[4] = (byte) (crc & 0xff);
   file.write(scratch, 0, 5);
   file.setLength(file.getFilePointer());
   saved += length;
   lastClock = clock;
   lastCrc = crc;
   if (size <= saved) {
     file.setLength(size);
     file.close();
     rename(partialFile, resultFile);
   }
 }
Beispiel #6
0
 public static void secureDelete(File file, Random random) throws IOException {
   // FIXME somebody who understands these things should have a look at this...
   if (!file.exists()) return;
   long size = file.length();
   if (size > 0) {
     RandomAccessFile raf = null;
     try {
       System.out.println(
           "Securely deleting " + file + " which is of length " + size + " bytes...");
       raf = new RandomAccessFile(file, "rw");
       raf.seek(0);
       long count;
       byte[] buf = new byte[4096];
       // First zero it out
       count = 0;
       while (count < size) {
         int written = (int) Math.min(buf.length, size - count);
         raf.write(buf, 0, written);
         count += written;
       }
       raf.getFD().sync();
       // Then ffffff it out
       for (int i = 0; i < buf.length; i++) buf[i] = (byte) 0xFF;
       raf.seek(0);
       count = 0;
       while (count < size) {
         int written = (int) Math.min(buf.length, size - count);
         raf.write(buf, 0, written);
         count += written;
       }
       raf.getFD().sync();
       // Then random data
       random.nextBytes(buf);
       raf.seek(0);
       count = 0;
       while (count < size) {
         int written = (int) Math.min(buf.length, size - count);
         raf.write(buf, 0, written);
         count += written;
       }
       raf.getFD().sync();
       raf.seek(0);
       // Then 0's again
       for (int i = 0; i < buf.length; i++) buf[i] = 0;
       count = 0;
       while (count < size) {
         int written = (int) Math.min(buf.length, size - count);
         raf.write(buf, 0, written);
         count += written;
       }
       raf.getFD().sync();
       raf.close();
       raf = null;
     } finally {
       Closer.close(raf);
     }
   }
   if ((!file.delete()) && file.exists()) throw new IOException("Unable to delete file " + file);
 }
Beispiel #7
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);
   }
 }
Beispiel #8
0
 private void persistTo(RandomAccessFile file) throws IOException {
   file.write(data.serializer.serialize(metadata()));
   file.write(CR_LF);
   for (Entry<Long, Rec> entry : data.data.entrySet()) {
     file.write(entry.getValue().bytes);
     file.write(CR_LF);
   }
 }
 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();
   }
 }
 public static void writeDbCommand2File(DbCommand cmd, RandomAccessFile randf) throws Exception {
   if (cmd == null) {
     return;
   }
   byte src[] = cmd.encode();
   randf.write((byte) (src.length >> 8));
   randf.write((byte) src.length);
   randf.write(src);
 }
Beispiel #11
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 static void writeSharesFile(RandomAccessFile out, ArrayList<Share> list)
     throws IOException {
   out.seek(0);
   for (int i = 0; i < list.size(); i++) {
     Share s = list.get(i);
     out.write(("" + s.getShareholderId() + "\n").getBytes());
     out.write((s.getCompanySymbol() + "\n").getBytes());
     out.write(("" + s.getAmountOfShares() + "\n").getBytes());
   }
 }
 private static void writeShareholdersFile(RandomAccessFile out, ArrayList<Shareholder> list)
     throws IOException {
   out.seek(0);
   for (int i = 0; i < list.size(); i++) {
     Shareholder s = list.get(i);
     out.write(("" + s.getShareholderId() + "\n").getBytes());
     out.write((s.getShareholderName() + "\n").getBytes());
     out.write(("" + s.isShareHolderActive() + "\n").getBytes());
   }
 }
 private static void writeCompaniesFile(RandomAccessFile out, ArrayList<Company> list)
     throws IOException {
   out.seek(0);
   for (int i = 0; i < list.size(); i++) {
     Company c = list.get(i);
     out.write((c.getCompanyName() + "\n").getBytes());
     out.write((c.getCompanySymbol() + "\n").getBytes());
     out.write(("" + c.getAmountOfShares() + "\n").getBytes());
     out.write(("" + c.getSharePrice() + "\n").getBytes());
   }
 }
 /**
  * This method uses the last valid bytes written on disk to position a {@link RandomAccessFile},
  * allowing resumable file download.
  *
  * @param buffer a {@link ByteBuffer}
  * @throws IOException
  */
 public void onBytesReceived(ByteBuffer buffer) throws IOException {
   file.seek(file.length());
   if (buffer.hasArray()) {
     file.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
   } else { // if the buffer is direct or backed by a String...
     byte[] b = new byte[buffer.remaining()];
     int pos = buffer.position();
     buffer.get(b);
     buffer.position(pos);
     file.write(b);
   }
 }
Beispiel #16
0
  protected static void persist(String content, String filePath, boolean append)
      throws IOException {
    // Remove string like <?xml version="1.0" encoding="UTF-8"?>
    // Pattern p = Pattern.compile("(<Comment\\W.*?</Comment>)");
    // Matcher m = p.matcher(content);
    File f = new File(filePath);
    File parent = f.getParentFile();
    if (!parent.exists()) parent.mkdirs();
    if (!f.exists()) f.createNewFile();

    RandomAccessFile raf = null;
    try {
      raf = new RandomAccessFile(f, "rw");
      if (!append) raf.setLength(0);
      byte[] buffer = new byte[1024];
      raf.read(buffer);
      String leadingString = new String(buffer).trim();
      Pattern p = Pattern.compile("(<\\?xml\\W.*?\\?>)");
      Matcher m = p.matcher(leadingString);
      String xmlMeta = ""; // Store the xml version meta data, used to insert to the xml file
      // if needed.
      if (m.find()) {
        xmlMeta = m.group();
      }
      leadingString = m.replaceAll("");
      leadingString =
          leadingString
              .substring(0, Math.min(leadingString.length(), "<CommentsDocument />".length()))
              .replaceAll("\\s", "");

      StringBuilder sb = new StringBuilder();
      content = content.replaceAll(p.pattern(), "");
      if (leadingString.startsWith("<CommentsDocument/>") || "".equals(leadingString)) {
        // There is no comments yet.
        raf.setLength(0);
        sb.append(xmlMeta);
        sb.append("<CommentsDocument>");
        sb.append(content);
        sb.append("</CommentsDocument>");
        raf.write(sb.toString().getBytes());
      } else if (leadingString.startsWith("<CommentsDocument>")) {
        // There are some comments and append new comments.
        long fileLen = raf.length() - "</CommentsDocument>".getBytes().length;
        raf.setLength(fileLen);
        raf.seek(raf.length());
        sb.append(content);
        sb.append("</CommentsDocument>");
        raf.write(sb.toString().getBytes());
      }
    } finally {
      if (raf != null) raf.close();
    }
  }
 /**
  * Prepare the data file used in the test.
  *
  * @return the file prepared.
  * @throws IOException on error
  */
 static File prepareTestDataFile() throws IOException { // NOPMD
   final File tmpFile = new File(NEWS_DATA_FILE_NAME);
   //
   final RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw");
   raf.write(NewsRecord.formatTitle(TITULO));
   raf.write(NewsRecord.formatDescription(DESCRIPCION));
   raf.write(NewsRecord.formatLink(LINK));
   raf.writeChar('r');
   //
   raf.close();
   return tmpFile;
 }
Beispiel #18
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);
    }
  }
Beispiel #19
0
 @Override
 public void writeLines(RAbstractStringVector lines, String sep, boolean useBytes)
     throws IOException {
   // TODO encodings
   raf.seek(writeOffset);
   byte[] sepData = sep.getBytes();
   for (int i = 0; i < lines.getLength(); i++) {
     byte[] data = lines.getDataAt(i).getBytes();
     raf.write(data);
     raf.write(sepData);
   }
   writeOffset = raf.getFilePointer();
   lastMode = SeekRWMode.WRITE;
 }
Beispiel #20
0
  public void commitChanges() throws IOException, RuntimeException {
    Throwable t = null;
    RandomAccessFile dataFile = null;
    try {
      try {
        dataFile = new RandomAccessFile(filePath, "rw");
      } catch (FileNotFoundException e) {
        throw new RuntimeException(filePath + " can't get access to file", e);
      }
      if (data == null || data.isEmpty()) {
        closeDataFile(dataFile);
        Shell sh = new Shell(tablePath, false);
        if (sh.rm(filePath) != Shell.ExitCode.OK) {
          throw new RuntimeException(filePath + " can't delete file");
        }
        exists = false;
        return;
      }

      int offset = 0;
      Set<Map.Entry<String, Storeable>> mySet = data.entrySet();
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        offset += getLength(myEntry.getKey()) + 1 + 4;
      }
      int currOffset = offset;
      dataFile.setLength(0);
      dataFile.seek(0);
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        dataFile.write(myEntry.getKey().getBytes());
        dataFile.writeByte(0);
        dataFile.writeInt(currOffset);
        currOffset += getLength(table.getProvider().serialize(table, myEntry.getValue()));
      }
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        dataFile.write(table.getProvider().serialize(table, myEntry.getValue()).getBytes());
      }
    } catch (RuntimeException e5) {
      t = e5;
      throw e5;
    } finally {
      try {
        closeDataFile(dataFile);
      } catch (Throwable e6) {
        if (t != null) {
          t.addSuppressed(e6);
        }
      }
    }
  }
  @Test
  public void testIsEncryptedFileTrue() throws Exception {
    File tempDirectory = TestFileUtil.createTempDirectoryInSystemTemp();
    File testFile = new File(tempDirectory + "/somefile");

    RandomAccessFile testFileRaf = new RandomAccessFile(testFile, "rw");

    testFileRaf.write(MultiCipherOutputStream.STREAM_MAGIC);
    testFileRaf.write(MultiCipherOutputStream.STREAM_VERSION);
    testFileRaf.close();

    assertTrue(CipherUtil.isEncrypted(testFile));

    TestFileUtil.deleteDirectory(tempDirectory);
  }
 private void insertLine(File file, HttpSample httpSample) throws IOException {
   RandomAccessFile randomAccessFile = null;
   try {
     randomAccessFile = new RandomAccessFile(file, "rw");
     randomAccessFile.skipBytes((int) (file.length() - "\n</httpSamples>".getBytes().length));
     randomAccessFile.write("\n".getBytes());
     randomAccessFile.write(httpSample.toXML().getBytes());
     randomAccessFile.write("\n".getBytes());
     randomAccessFile.write("</httpSamples>".getBytes());
   } finally {
     if (randomAccessFile != null) {
       randomAccessFile.close();
     }
   }
 }
Beispiel #23
0
  /** Write NumBytes data. */
  public int Write(RiffChunkHeader Triff_header, int NumBytes) {
    byte[] br = new byte[8];
    br[0] = (byte) ((Triff_header.ckID >>> 24) & 0x000000FF);
    br[1] = (byte) ((Triff_header.ckID >>> 16) & 0x000000FF);
    br[2] = (byte) ((Triff_header.ckID >>> 8) & 0x000000FF);
    br[3] = (byte) (Triff_header.ckID & 0x000000FF);

    byte br4 = (byte) ((Triff_header.ckSize >>> 24) & 0x000000FF);
    byte br5 = (byte) ((Triff_header.ckSize >>> 16) & 0x000000FF);
    byte br6 = (byte) ((Triff_header.ckSize >>> 8) & 0x000000FF);
    byte br7 = (byte) (Triff_header.ckSize & 0x000000FF);

    br[4] = br7;
    br[5] = br6;
    br[6] = br5;
    br[7] = br4;

    if (fmode != RFM_WRITE) {
      return DDC_INVALID_CALL;
    }
    try {
      file.write(br, 0, NumBytes);
      fmode = RFM_WRITE;
    } catch (IOException ioe) {
      return DDC_FILE_ERROR;
    }
    riff_header.ckSize += NumBytes;
    return DDC_SUCCESS;
  }
Beispiel #24
0
Datei: AR.java Projekt: zhaog/cdt
  public String[] extractFiles(String outdir, String[] names) throws IOException {
    Vector<String> names_used = new Vector<String>();
    String object_name;
    int count;

    loadHeaders();

    count = 0;
    for (MemberHeader memberHeader : memberHeaders) {
      object_name = memberHeader.getObjectName();
      if (names != null && !stringInStrings(object_name, names)) continue;

      object_name = "" + count + "_" + object_name; // $NON-NLS-1$ //$NON-NLS-2$
      count++;

      byte[] data = memberHeader.getObjectData();
      File output = new File(outdir, object_name);
      names_used.add(object_name);

      RandomAccessFile rfile = new RandomAccessFile(output, "rw"); // $NON-NLS-1$
      rfile.write(data);
      rfile.close();
    }

    return names_used.toArray(new String[0]);
  }
    @Override
    public void write(byte[] buffer, int offset, int count) throws IOException {

      super.write(buffer, offset, count);
      progress += count;
      publishProgress(progress);
    }
 /**
  * Write bytes to output or random access file.
  *
  * @param data the byte array to write
  * @param offset the start position to write from
  * @param length the number of bytes to write
  * @throws IOException on error
  */
 protected final void writeOut(byte[] data, int offset, int length) throws IOException {
   if (raf != null) {
     raf.write(data, offset, length);
   } else {
     out.write(data, offset, length);
   }
 }
Beispiel #27
0
    @Override
    public void run() {
      try {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
            "Accept",
            "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                + "application/x-shockwave-flash, application/xaml+xml, "
                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                + "application/x-ms-application, application/vnd.ms-excel, "
                + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");

        InputStream inputStream = conn.getInputStream();

        // 跳过startPos那一部分内容,表明该线程仅下载属于它自己的那一部分
        inputStream.skip(this.startPos);

        byte[] bytes = new byte[1024];
        int hasRead = 0;
        while (length < currentPartSize && (hasRead = inputStream.read(bytes)) != -1) {
          currentPart.write(bytes, 0, hasRead);
          length += hasRead;
        }
        currentPart.close();
        inputStream.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Beispiel #28
0
  public void newCheckpoint(byte[] state, byte[] stateHash, int consensusId) {
    String ckpPath = DEFAULT_DIR + String.valueOf(id) + "." + System.currentTimeMillis() + ".tmp";
    try {
      checkpointLock.lock();
      RandomAccessFile ckp = new RandomAccessFile(ckpPath, (syncCkp ? "rwd" : "rw"));

      ByteBuffer bf = ByteBuffer.allocate(state.length + stateHash.length + 4 * INT_BYTE_SIZE);
      bf.putInt(state.length);
      bf.put(state);
      bf.putInt(stateHash.length);
      bf.put(stateHash);
      bf.putInt(EOF);
      bf.putInt(consensusId);

      byte[] ckpState = bf.array();

      ckp.write(ckpState);
      ckp.close();

      if (isToLog) deleteLogFile();
      deleteLastCkp();
      renameCkp(ckpPath);
      if (isToLog) createLogFile();

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      checkpointLock.unlock();
    }
  }
Beispiel #29
0
 void corruptFile(int position) throws Exception {
   File file = new File(getDirectory(), "transaction.log");
   RandomAccessFile ra = new RandomAccessFile(file, "rw");
   ra.seek(position);
   ra.write(0xff);
   ra.close();
 }
Beispiel #30
0
 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();
   }
 }