java.io.RandomAccessFile#seek ( )源码实例Demo

下面列出了java.io.RandomAccessFile#seek ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop   文件: MiniDFSCluster.java
public static boolean corruptBlock(File blockFile) throws IOException {
  if (blockFile == null || !blockFile.exists()) {
    return false;
  }
  // Corrupt replica by writing random bytes into replica
  Random random = new Random();
  RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
  FileChannel channel = raFile.getChannel();
  String badString = "BADBAD";
  int rand = random.nextInt((int)channel.size()/2);
  raFile.seek(rand);
  raFile.write(badString.getBytes());
  raFile.close();
  LOG.warn("Corrupting the block " + blockFile);
  return true;
}
 
源代码2 项目: openjdk-jdk8u   文件: TestRecordingFile.java
private static Path createBrokenWIthZeros(Path valid) throws Exception {
    try {
        Path broken = Utils.createTempFile("broken-events", ".jfr");
        Files.delete(broken);
        Files.copy(valid, broken);
        RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
        raf.seek(HEADER_SIZE);
        int size = (int) Files.size(broken);
        byte[] ones = new byte[size - HEADER_SIZE];
        for (int i = 0; i < ones.length; i++) {
            ones[i] = (byte) 0xFF;
        }
        raf.write(ones, 0, ones.length);
        raf.close();
        return broken;
    } catch (IOException ioe) {
        throw new Exception("Could not produce a broken file " + valid, ioe);
    }
}
 
源代码3 项目: big-c   文件: NativeIO.java
/**
 * Create a FileInputStream that shares delete permission on the
 * file opened at a given offset, i.e. other process can delete
 * the file the FileInputStream is reading. Only Windows implementation
 * uses the native interface.
 */
public static FileInputStream getShareDeleteFileInputStream(File f, long seekOffset)
    throws IOException {
  if (!Shell.WINDOWS) {
    RandomAccessFile rf = new RandomAccessFile(f, "r");
    if (seekOffset > 0) {
      rf.seek(seekOffset);
    }
    return new FileInputStream(rf.getFD());
  } else {
    // Use Windows native interface to create a FileInputStream that
    // shares delete permission on the file opened, and set it to the
    // given offset.
    //
    FileDescriptor fd = NativeIO.Windows.createFile(
        f.getAbsolutePath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
            NativeIO.Windows.FILE_SHARE_WRITE |
            NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    if (seekOffset > 0)
      NativeIO.Windows.setFilePointer(fd, seekOffset, NativeIO.Windows.FILE_BEGIN);
    return new FileInputStream(fd);
  }
}
 
源代码4 项目: cloudstack   文件: HttpTemplateDownloader.java
private long writeBlock(int bytes, RandomAccessFile out, byte[] block, long offset) throws IOException {
    out.write(block, 0, bytes);
    offset += bytes;
    out.seek(offset);
    totalBytes += bytes;
    return offset;
}
 
源代码5 项目: BPlusTree   文件: TreeInternalNode.java
/**
 *
 *  Internal node structure is as follows:
 *
 *  -- node type -- (2 bytes)
 *  -- current capacity -- (4 bytes)
 *
 *  -- Key -- (8 bytes max size)
 *
 *  -- Pointers (8 bytes max size + 1)
 *
 *  we go like: k1 -- p0 -- k2 -- p1 ... kn -- pn+1
 *
 * @param r pointer to *opened* B+ tree file
 * @throws IOException is thrown when an I/O exception is captured.
 */
@Override
public void writeNode(RandomAccessFile r, BPlusConfiguration conf,
                      BPlusTreePerformanceCounter bPerf)
        throws IOException {

    // update root index in the file
    if(this.isRoot()) {
        r.seek(conf.getHeaderSize()-8);
        r.writeLong(getPageIndex());
    }

    // account for the header page as well.
    r.seek(getPageIndex());

    // write the node type
    r.writeShort(getPageType());

    // write current capacity
    r.writeInt(getCurrentCapacity());

    // now write Key/Pointer pairs
    for(int i = 0; i < getCurrentCapacity(); i++) {
        r.writeLong(getKeyAt(i));       // Key
        r.writeLong(getPointerAt(i));   // Pointer
    }
    // final pointer.
    r.writeLong(getPointerAt(getCurrentCapacity()));

    // annoying correction
    if(r.length() < getPageIndex()+conf.getPageSize())
        {r.setLength(getPageIndex()+conf.getPageSize());}

    bPerf.incrementTotalInternalNodeWrites();
}
 
源代码6 项目: hadoop   文件: TestFileJournalManager.java
/** 
 * Corrupt an edit log file after the start segment transaction
 */
private void corruptAfterStartSegment(File f) throws IOException {
  RandomAccessFile raf = new RandomAccessFile(f, "rw");
  raf.seek(0x20); // skip version and first tranaction and a bit of next transaction
  for (int i = 0; i < 1000; i++) {
    raf.writeInt(0xdeadbeef);
  }
  raf.close();
}
 
源代码7 项目: PortEx   文件: IOUtil.java
private static int nullTerminatorIndex(long offset, RandomAccessFile raf)
		throws IOException {
	raf.seek(offset);
	int index = 0;
	byte b;
	do {
		b = raf.readByte();
		index++;
	} while (b != 0);
	return index;
}
 
源代码8 项目: j2objc   文件: RandomAccessFileTest.java
/**
 * java.io.RandomAccessFile#readLine()
 */
public void test_readLine() throws IOException {
    // Test for method java.lang.String java.io.RandomAccessFile.readLine()
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    String s = "Goodbye\nCruel\nWorld\n";
    raf.write(s.getBytes("UTF-8"), 0, s.length());
    raf.seek(0);

    assertEquals("Goodbye", raf.readLine());
    assertEquals("Cruel", raf.readLine());
    assertEquals("World", raf.readLine());

    raf.close();
}
 
源代码9 项目: ViewDebugHelper   文件: CrashHandler.java
public static void writeToFile(String fileName, String msg) throws IOException {
    File file=new File(fileName);
    if(file.exists()&&file.length()>1024*1024*5){//>5M
        file.delete();
    }
    if(!file.exists())
        file.createNewFile();
    RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
    long fileLength = randomFile.length();
    randomFile.seek(fileLength);
    randomFile.write(msg.getBytes());
    randomFile.close();
}
 
源代码10 项目: big-c   文件: TestFSEditLogLoader.java
@Test
public void testValidateEditLogWithCorruptHeader() throws IOException {
  File testDir = new File(TEST_DIR, "testValidateEditLogWithCorruptHeader");
  SortedMap<Long, Long> offsetToTxId = Maps.newTreeMap();
  File logFile = prepareUnfinalizedTestEditLog(testDir, 2, offsetToTxId);
  RandomAccessFile rwf = new RandomAccessFile(logFile, "rw");
  try {
    rwf.seek(0);
    rwf.writeLong(42); // corrupt header
  } finally {
    rwf.close();
  }
  EditLogValidation validation = EditLogFileInputStream.validateEditLog(logFile);
  assertTrue(validation.hasCorruptHeader());
}
 
源代码11 项目: sbt-android-protify   文件: ZipUtil.java
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;
}
 
源代码12 项目: COLA   文件: ServiceListStore.java
public void save(String content) {
    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(raf.length());
        writeLine(raf, content);
        raf.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码13 项目: Flashtool   文件: SinParser.java
public void dumpImage() throws IOException {
	try {
		RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
		logger.info("Generating container file");
		String ext = "."+getDataType();
		String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+ext;
		RandomAccessFile fout = OS.generateEmptyFile(foutname, dataSize, (byte)0xFF);
		logger.info("Finished Generating container file");
		// Positionning in files
		logger.info("Extracting data into container");
		fin.seek(headerLen);
		LogProgress.initProgress(blocks.block.length);
		for (int i=0;i<blocks.block.length;i++) {
			HashBlock b = blocks.block[i];
			byte[] data = new byte[b.length];
			fin.read(data);
			if (!b.validate(data)) throw new Exception("Corrupted data");
			fout.seek(blocks.block.length==1?0:b.offset);
			fout.write(data);
			LogProgress.updateProgress();
		}
		LogProgress.initProgress(0);
		fout.close();
		logger.info("Extraction finished to "+foutname);
	}
	catch (Exception e) {
		logger.error("Error while extracting data : "+e.getMessage());
		LogProgress.initProgress(0);
		e.printStackTrace();
	}
}
 
源代码14 项目: Nukkit   文件: RegionLoader.java
@Override
protected void saveChunk(int x, int z, byte[] chunkData) throws IOException {
    int length = chunkData.length + 1;
    if (length + 4 > MAX_SECTOR_LENGTH) {
        throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH);
    }
    int sectors = (int) Math.ceil((length + 4) / 4096d);
    int index = getChunkOffset(x, z);
    boolean indexChanged = false;
    Integer[] table = this.locationTable.get(index);

    if (table[1] < sectors) {
        table[0] = this.lastSector + 1;
        this.locationTable.put(index, table);
        this.lastSector += sectors;
        indexChanged = true;
    } else if (table[1] != sectors) {
        indexChanged = true;
    }

    table[1] = sectors;
    table[2] = (int) (System.currentTimeMillis() / 1000d);

    this.locationTable.put(index, table);
    RandomAccessFile raf = this.getRandomAccessFile();
    raf.seek(table[0] << 12);

    BinaryStream stream = new BinaryStream();
    stream.put(Binary.writeInt(length));
    stream.putByte(COMPRESSION_ZLIB);
    stream.put(chunkData);
    byte[] data = stream.getBuffer();
    if (data.length < sectors << 12) {
        byte[] newData = new byte[sectors << 12];
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
    }

    raf.write(data);

    if (indexChanged) {
        this.writeLocationIndex(index);
    }
}
 
源代码15 项目: jdk8u-jdk   文件: Basic.java
public static void main(String[] args) throws Exception {

        show(nonExistantFile);
        if (nonExistantFile.exists()) fail(nonExistantFile, "exists");

        show(rwFile);
        testFile(rwFile, true, 6);
        rwFile.delete();
        if (rwFile.exists())
            fail(rwFile, "could not delete");

        show(roFile);
        testFile(roFile, false, 0);

        show(thisDir);
        if (!thisDir.exists()) fail(thisDir, "does not exist");
        if (thisDir.isFile()) fail(thisDir, "is a file");
        if (!thisDir.isDirectory()) fail(thisDir, "is not a directory");
        if (!thisDir.canRead()) fail(thisDir, "is readable");
        if (!thisDir.canWrite()) fail(thisDir, "is writeable");
        String[] fs = thisDir.list();
        if (fs == null) fail(thisDir, "list() returned null");
        out.print("  [" + fs.length + "]");
        for (int i = 0; i < fs.length; i++)
            out.print(" " + fs[i]);
        out.println();
        if (fs.length == 0) fail(thisDir, "is empty");

        if (!nonExistantFile.createNewFile())
            fail(nonExistantFile, "could not create");
        nonExistantFile.deleteOnExit();

        if (!nonDir.mkdir())
            fail(nonDir, "could not create");

        if (!dir.renameTo(new File("x.Basic.dir2")))
            fail(dir, "failed to rename");

        if (System.getProperty("os.name").equals("SunOS")
            && System.getProperty("os.version").compareTo("5.6") >= 0) {
            if (bigFile.exists()) {
                bigFile.delete();
                if (bigFile.exists())
                    fail(bigFile, "could not delete");
            }
            RandomAccessFile raf = new RandomAccessFile(bigFile, "rw");
            long big = ((long)Integer.MAX_VALUE) * 2;
            try {
                raf.seek(big);
                raf.write('x');
                show(bigFile);
                testFile(bigFile, true, big + 1);
            } finally {
                raf.close();
            }
            bigFile.delete();
            if (bigFile.exists())
                fail(bigFile, "could not delete");
        } else {
            System.err.println("NOTE: Large files not supported on this system");
        }

    }
 
源代码16 项目: Bytecoder   文件: ModelByteBuffer.java
RandomFileInputStream() throws IOException {
    raf = new RandomAccessFile(root.file, "r");
    raf.seek(root.fileoffset + arrayOffset());
    left = capacity();
}
 
源代码17 项目: Nukkit   文件: RegionLoader.java
@Override
protected void saveChunk(int x, int z, byte[] chunkData) throws IOException {
    int length = chunkData.length + 1;
    if (length + 4 > MAX_SECTOR_LENGTH) {
        throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH);
    }
    int sectors = (int) Math.ceil((length + 4) / 4096d);
    int index = getChunkOffset(x, z);
    boolean indexChanged = false;
    Integer[] table = this.locationTable.get(index);

    if (table[1] < sectors) {
        table[0] = this.lastSector + 1;
        this.locationTable.put(index, table);
        this.lastSector += sectors;
        indexChanged = true;
    } else if (table[1] != sectors) {
        indexChanged = true;
    }

    table[1] = sectors;
    table[2] = (int) (System.currentTimeMillis() / 1000d);

    this.locationTable.put(index, table);

    RandomAccessFile raf = this.getRandomAccessFile();
    raf.seek(table[0] << 12);

    BinaryStream stream = new BinaryStream();
    stream.put(Binary.writeInt(length));
    stream.putByte(COMPRESSION_ZLIB);
    stream.put(chunkData);
    byte[] data = stream.getBuffer();
    if (data.length < sectors << 12) {
        byte[] newData = new byte[sectors << 12];
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
    }

    raf.write(data);

    if (indexChanged) {
        this.writeLocationIndex(index);
    }

}
 
源代码18 项目: document-management-system   文件: TailServlet.java
/**
 * Do the magic
 */
private void tail(File file, PrintWriter out, int timeout) throws InterruptedException, IOException {
	long filePointer = 0;
	int toLeave = 0;
	int row = 0;
	out.println("<table class=\"results\" width=\"90%\">");
	out.println("<tr><th>#</th><th>Line</th></tr>");

	while (true) {
		long len = file.length();

		if (len < filePointer) {
			// Log must have been shorted or deleted.
			out.print("<tr class=\"fuzzy\"><td colspan=\"2\" align=\"center\">");
			out.print("<b>Log file was reset. Restarting logging from start of file.</b>");
			out.println("</td></tr>");
			out.flush();
			filePointer = 0;
			row = 0;
			toLeave = 0;
		} else if (len > filePointer) {
			// File must have had something added to it!
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			raf.seek(filePointer);
			String line = null;

			while ((line = raf.readLine()) != null) {
				out.print("<tr class=\"" + (row++ % 2 == 0 ? "even" : "odd") + "\">");
				out.print("<td>" + row + "</td><td>");
				out.print(FormatUtil.escapeHtml(new String(line.getBytes("ISO-8859-1"), "UTF-8")));
				out.println("</td></tr>");
				out.flush();
			}

			filePointer = raf.getFilePointer();
			raf.close();
			toLeave = 0;
		} else {
			if (toLeave++ > timeout) {
				break;
			}
		}

		Thread.sleep(1000);
	}

	out.print("<tr class=\"fuzzy\"><td colspan=\"2\" align=\"center\">");
	out.print("<b>Log file was not modified for " + timeout + " seconds</b>");
	out.println("</td></tr>");
	out.println("</table>");
}
 
源代码19 项目: netbeans   文件: FastJar.java
private static final void seekBy(final RandomAccessFile b, int offset) throws IOException {
    b.seek(b.getFilePointer() + offset);
}
 
源代码20 项目: dragonwell8_jdk   文件: ModelByteBuffer.java
RandomFileInputStream() throws IOException {
    raf = new RandomAccessFile(root.file, "r");
    raf.seek(root.fileoffset + arrayOffset());
    left = capacity();
}