java.io.RandomAccessFile Java Examples
The following examples show how to use
java.io.RandomAccessFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WikipediaTest.java From minperf with Apache License 2.0 | 7 votes |
private static void largeFile(String fileName) throws IOException { if (!new File(fileName).exists()) { System.out.println("not found: " + fileName); return; } RandomAccessFile f = new RandomAccessFile(fileName, "r"); byte[] data = new byte[(int) f.length()]; f.readFully(data); HashSet<Text> set = new HashSet<Text>(40 * 1024 * 1024); int end = Text.indexOf(data, 0, '\n'); Text t = new Text(data, 0, end); long time = System.currentTimeMillis(); while (true) { set.add(t); if (end >= data.length - 1) { break; } int start = end + 1; end = Text.indexOf(data, start, '\n'); t = new Text(data, start, end - start); long now = System.currentTimeMillis(); if (now - time > 2000) { System.out.println("size: " + set.size()); time = now; } } System.out.println("file: " + fileName); System.out.println("size: " + set.size()); test(set, 8, 14); test(set, 8, 10); test(set, 8, 16); test(set, 8, 12); }
Example #2
Source File: JdpDoSomething.java From openjdk-8-source with GNU General Public License v2.0 | 7 votes |
public static void printJdpPacket(JdpJmxPacket p) { if (getVerbose()) { try { RandomAccessFile f = new RandomAccessFile("out.dmp", "rw"); f.write(p.getPacketData()); f.close(); } catch (IOException e) { System.out.println("Can't write a dump file: " + e); } System.out.println("Id: " + p.getId()); System.out.println("Jmx: " + p.getJmxServiceUrl()); System.out.println("Main: " + p.getMainClass()); System.out.println("InstanceName: " + p.getInstanceName()); System.out.println("ProccessId: " + p.getProcessId()); System.out.println("BroadcastInterval: " + p.getBroadcastInterval()); System.out.println("Rmi Hostname: " + p.getRmiHostname()); System.out.flush(); } }
Example #3
Source File: OldRandomAccessFileTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * java.io.RandomAccessFile#writeChars(java.lang.String) */ public void test_writeCharsLjava_lang_String() throws IOException { RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); raf.writeChars(unihw); char[] hchars = new char[unihw.length()]; unihw.getChars(0, unihw.length(), hchars, 0); raf.seek(0); for (int i = 0; i < hchars.length; i++) assertEquals("Test 1: Incorrect character written or read at index " + i + ";", hchars[i], raf.readChar()); raf.close(); try { raf.writeChars("Already closed."); fail("Test 2: IOException expected."); } catch (IOException e) { // Expected. } }
Example #4
Source File: FileChange.java From Green-Creator with GNU General Public License v2.0 | 6 votes |
public FileChange(File file) throws IOException { if(!file.exists()) { System.out.println("File not found"); throw new IOException(); } this.file = file; RandomAccessFile rsf = new RandomAccessFile(this.file, "rw"); this.data = new byte[(int) rsf.length()]; rsf.read(data); int pos = 0; while (pos < data.length) { instBuf.add(data[pos++]); } rsf.close(); getLength(); }
Example #5
Source File: BaseRegionLoader.java From Jupiter with GNU General Public License v3.0 | 6 votes |
public BaseRegionLoader(LevelProvider level, int regionX, int regionZ, String ext) { try { this.x = regionX; this.z = regionZ; this.levelProvider = level; this.filePath = this.levelProvider.getPath() + "region/r." + regionX + "." + regionZ + "." + ext; this.file = new File(this.filePath); boolean exists = this.file.exists(); if (!exists) { file.createNewFile(); } this.randomAccessFile = new RandomAccessFile(this.filePath, "rw"); if (!exists) { this.createBlank(); } else { this.loadLocationTable(); } this.lastUsed = System.currentTimeMillis(); } catch (IOException e) { throw new RuntimeException(e); } }
Example #6
Source File: TwoBitParser.java From biojava with GNU Lesser General Public License v2.1 | 6 votes |
public TwoBitParser(File f) throws Exception { this.f = f; raf = new RandomAccessFile(f,"r"); long sign = readFourBytes(); if(sign==0x1A412743) { logger.debug("2bit: Normal number architecture"); } else if(sign==0x4327411A) { reverse = true; logger.debug("2bit: Reverse number architecture"); } else throw new Exception("Wrong start signature in 2BIT format"); readFourBytes(); int seq_qnt = (int)readFourBytes(); readFourBytes(); seq_names = new String[seq_qnt]; for(int i=0;i<seq_qnt;i++) { int name_len = raf.read(); char[] chars = new char[name_len]; for(int j=0;j<name_len;j++) chars[j] = (char)raf.read(); seq_names[i] = new String(chars); long pos = readFourBytes(); seq2pos.put(seq_names[i],pos); logger.debug("2bit: Sequence name=[{}], pos={}", seq_names[i], pos); } }
Example #7
Source File: RandomAccessFileDemo.java From code with Apache License 2.0 | 6 votes |
@Test public void testRead() throws IOException { // 1、创建随机访问流对象 RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw"); int i = raf.readInt(); System.out.println(i); // 该文件指针可以通过 getFilePointer方法读取,并通过 seek 方法设置。 System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); char ch = raf.readChar(); System.out.println(ch); System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); String s = raf.readUTF(); System.out.println(s); System.out.println("当前文件的指针位置是:" + raf.getFilePointer()); // 我不想重头开始了,我就要读取a,怎么办呢? raf.seek(4); ch = raf.readChar(); System.out.println(ch); }
Example #8
Source File: FileSystemFileConnection.java From J2ME-Loader with Apache License 2.0 | 6 votes |
private OutputStream openOutputStream(boolean appendToFile, final long byteOffset) throws IOException { throwClosed(); throwOpenDirectory(); if (this.opendOutputStream != null) { throw new IOException("OutputStream already opened"); } /** * Trying to open more than one InputStream or more than one * OutputStream from a StreamConnection causes an IOException. */ RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(byteOffset); return new FileOutputStream(raf.getFD()) { @Override public void close() throws IOException { FileSystemFileConnection.this.opendOutputStream = null; super.close(); } }; }
Example #9
Source File: AbstractFileCheckpointCollection.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
/** * Marks the index as dirty. Writes an invalid file header, and sets the dirty * flag which will cause the new file header to be serialized when the index is * disposed. */ protected void markDirty() { RandomAccessFile randomAccessFile = fRandomAccessFile; if (fIsDirty || randomAccessFile == null) { return; } try { // Write an invalid version until the very last moment when dispose // the index. This is how we know if it's corrupted or not. randomAccessFile.seek(0); randomAccessFile.writeInt(INVALID_VERSION); } catch (IOException e) { Activator.logError(MessageFormat.format(Messages.IOErrorWritingHeader, fFile), e); } fIsDirty = true; }
Example #10
Source File: LockPatternUtils.java From quickmark with MIT License | 6 votes |
/** * Check to see if a pattern matches the saved pattern. If no pattern * exists, always returns true. * * @param pattern * The pattern to check. * @return Whether the pattern matches the stored one. */ public boolean checkPattern(List<LockPatternView.Cell> pattern) { try { // Read all the bytes from the file RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r"); final byte[] stored = new byte[(int) raf.length()]; int got = raf.read(stored, 0, stored.length); raf.close(); if (got <= 0) { return true; } // Compare the hash from the file with the entered pattern's hash return Arrays.equals(stored, LockPatternUtils.patternToHash(pattern)); } catch (FileNotFoundException fnfe) { return true; } catch (IOException ioe) { return true; } }
Example #11
Source File: VLCUtil.java From vlc-example-streamplayer with GNU General Public License v3.0 | 6 votes |
private static boolean readSection(RandomAccessFile in, ElfData elf) throws IOException { byte[] bytes = new byte[SECTION_HEADER_SIZE]; in.seek(elf.e_shoff); for (int i = 0; i < elf.e_shnum; ++i) { in.readFully(bytes); // wrap bytes in a ByteBuffer to force endianess ByteBuffer buffer = ByteBuffer.wrap(bytes); buffer.order(elf.order); int sh_type = buffer.getInt(4); /* Section type */ if (sh_type != SHT_ARM_ATTRIBUTES) continue; elf.sh_offset = buffer.getInt(16); /* Section file offset */ elf.sh_size = buffer.getInt(20); /* Section size in bytes */ return true; } return false; }
Example #12
Source File: OverlappedTrainingRunner.java From sgdtk with Apache License 2.0 | 6 votes |
private void passN() throws IOException { // Get FV from file randomAccessFile = new RandomAccessFile(getCacheFile(), "r"); while (randomAccessFile.getFilePointer() < randomAccessFile.length()) { int recordLength = (int) randomAccessFile.readLong(); packBuffer = growIfNeeded(packBuffer, recordLength); randomAccessFile.read(packBuffer, 0, recordLength); FeatureVector fv = toFeatureVector(); // add to ring buffer addWithProb(fv); } randomAccessFile.close(); signalEndEpoch(); }
Example #13
Source File: OldRandomAccessFileTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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(), 0, s.length()); raf.seek(0); assertEquals("Test 1: Incorrect line read;", "Goodbye", raf.readLine()); assertEquals("Test 2: Incorrect line read;", "Cruel", raf.readLine()); assertEquals("Test 3: Incorrect line read;", "World", raf.readLine()); assertNull("Test 4: Incorrect line read; null expected.", raf.readLine()); raf.close(); try { raf.readLine(); fail("Test 5: IOException expected."); } catch (IOException e) { // Expected. } }
Example #14
Source File: FileIOEngine.java From hbase with Apache License 2.0 | 6 votes |
@VisibleForTesting void refreshFileConnection(int accessFileNum, IOException ioe) throws IOException { ReentrantLock channelLock = channelLocks[accessFileNum]; channelLock.lock(); try { FileChannel fileChannel = fileChannels[accessFileNum]; if (fileChannel != null) { // Don't re-open a channel if we were waiting on another // thread to re-open the channel and it is now open. if (fileChannel.isOpen()) { return; } fileChannel.close(); } LOG.warn("Caught ClosedChannelException accessing BucketCache, reopening file: " + filePaths[accessFileNum], ioe); rafs[accessFileNum] = new RandomAccessFile(filePaths[accessFileNum], "rw"); fileChannels[accessFileNum] = rafs[accessFileNum].getChannel(); } finally{ channelLock.unlock(); } }
Example #15
Source File: DiskInitFile.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
private void openRAF() { if (DiskStoreImpl.PREALLOCATE_IF) { openRAF2(); return; } try { this.ifRAF = new RandomAccessFile(this.ifFile, getFileMode()); long len = this.ifRAF.length(); if (len != 0) { this.ifRAF.seek(len); } } catch (IOException ex) { throw new DiskAccessException( LocalizedStrings.DiskRegion_COULD_NOT_OPEN_0.toLocalizedString(this.ifFile .getPath()), ex, this.parent); } }
Example #16
Source File: BufferUtil.java From MikuMikuStudio with BSD 2-Clause "Simplified" License | 6 votes |
private static ByteBuffer createByteBufferFile(int size) { try { if (tmpDir != null && logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "tmpDir = {0}", tmpDir.getAbsoluteFile()); } File tmpFile = File.createTempFile("pmd","tmp", tmpDir); if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "tmpFile = {0}", tmpFile.getAbsoluteFile()); } RandomAccessFile os = new RandomAccessFile(tmpFile, "rw"); os.seek(size); os.write(0); FileChannel ch = os.getChannel(); MappedByteBuffer bb = ch.map(MapMode.READ_WRITE, 0, size); os.close(); ch.close(); tmpFile.delete(); bb.order(ByteOrder.nativeOrder()); return bb; } catch(IOException ex) { throw new RuntimeException(ex); } }
Example #17
Source File: PersistentFile.java From graphicsfuzz with Apache License 2.0 | 6 votes |
@Override public byte[] load(String key) { String filename = makeFilename(key); File file = new File(filename); if (!file.exists()) { return null; } byte[] data = null; try { RandomAccessFile f = new RandomAccessFile(file, "r"); data = new byte[(int) file.length()]; f.readFully(data); f.close(); } catch (Exception e) { e.printStackTrace(); } return data; }
Example #18
Source File: TrackManager.java From trekarta with GNU General Public License v3.0 | 6 votes |
/** * Saves track properties by modifying only file tail. */ public void saveProperties(FileDataSource source) throws Exception { Track track = source.tracks.get(0); // Prepare new properties tail ByteBuffer buffer = ByteBuffer.allocate(getSerializedPropertiesSize(track)); CodedOutputStream output = CodedOutputStream.newInstance(buffer); output.writeBytes(FIELD_NAME, ByteString.copyFromUtf8(track.name)); output.writeUInt32(FIELD_COLOR, track.style.color); output.writeFloat(FIELD_WIDTH, track.style.width); output.flush(); // Modify tail of file File file = new File(source.path); long createTime = file.lastModified(); RandomAccessFile access = new RandomAccessFile(file, "rw"); access.setLength(source.propertiesOffset + 1); access.seek(source.propertiesOffset); access.write(buffer.array()); access.close(); //noinspection ResultOfMethodCallIgnored file.setLastModified(createTime); }
Example #19
Source File: JdpDoSomething.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void printJdpPacket(JdpJmxPacket p) { if (getVerbose()) { try { RandomAccessFile f = new RandomAccessFile("out.dmp", "rw"); f.write(p.getPacketData()); f.close(); } catch (IOException e) { System.out.println("Can't write a dump file: " + e); } System.out.println("Id: " + p.getId()); System.out.println("Jmx: " + p.getJmxServiceUrl()); System.out.println("Main: " + p.getMainClass()); System.out.println("InstanceName: " + p.getInstanceName()); System.out.println("ProccessId: " + p.getProcessId()); System.out.println("BroadcastInterval: " + p.getBroadcastInterval()); System.out.println("Rmi Hostname: " + p.getRmiHostname()); System.out.flush(); } }
Example #20
Source File: TestEventQueueBackingStoreFactory.java From mt-flume with Apache License 2.0 | 6 votes |
@Test (expected = InvalidProtocolBufferException.class) public void testCorruptMeta() throws Throwable { EventQueueBackingStore backingStore = EventQueueBackingStoreFactory. get(checkpoint, 10, "test"); backingStore.close(); Assert.assertTrue(checkpoint.exists()); File metaFile = Serialization.getMetaDataFile(checkpoint); Assert.assertTrue(metaFile.length() != 0); RandomAccessFile writer = new RandomAccessFile(metaFile, "rw"); writer.seek(10); writer.writeLong(new Random().nextLong()); writer.getFD().sync(); writer.close(); try { backingStore = EventQueueBackingStoreFactory.get(checkpoint, 10, "test"); } catch (BadCheckpointException ex) { throw ex.getCause(); } }
Example #21
Source File: SegmentImpl.java From xdm with GNU General Public License v2.0 | 6 votes |
public SegmentImpl(String folder, String id, long off, long len, long dwn) throws IOException { this.id = id; this.id = id; this.startOffset = off; this.folder = folder; this.length = len; this.downloaded = dwn; this.time1 = System.currentTimeMillis(); this.time2 = time1; this.bytesRead1 = dwn; this.bytesRead2 = dwn; try { outStream = new RandomAccessFile(new File(folder, id), "rw"); outStream.seek(dwn); Logger.log("File opened " + id); } catch (IOException e) { Logger.log(e); if (outStream != null) { outStream.close(); } throw new IOException(e); } this.config = Config.getInstance(); }
Example #22
Source File: NNStorage.java From big-c with Apache License 2.0 | 6 votes |
@Override // Storage public boolean isPreUpgradableLayout(StorageDirectory sd) throws IOException { if (disablePreUpgradableLayoutCheck) { return false; } File oldImageDir = new File(sd.getRoot(), "image"); if (!oldImageDir.exists()) { return false; } // check the layout version inside the image file File oldF = new File(oldImageDir, "fsimage"); RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); oldFile.close(); oldFile = null; if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) return false; } finally { IOUtils.cleanup(LOG, oldFile); } return true; }
Example #23
Source File: StreamUtils.java From netbeans with Apache License 2.0 | 6 votes |
public static void transferFile( final File file, final OutputStream out, final Progress progress) throws IOException { RandomAccessFile in = null; try { transferData(in = new RandomAccessFile(file, "r"), out, progress); } finally { if (in != null) { try { in.close(); } catch (IOException e) { ErrorManager.notifyDebug("Cannot close raf", e); } } } }
Example #24
Source File: LossReportTestUtil.java From aeron with Apache License 2.0 | 5 votes |
public static void verifyLossOccurredForStream(final String aeronDirectoryName, final int streamId) throws IOException { final File lossReportFile = LossReportUtil.file(aeronDirectoryName); assertTrue(lossReportFile.exists()); MappedByteBuffer mappedByteBuffer = null; try (RandomAccessFile file = new RandomAccessFile(lossReportFile, "r"); FileChannel channel = file.getChannel()) { mappedByteBuffer = channel.map(READ_ONLY, 0, channel.size()); final AtomicBuffer buffer = new UnsafeBuffer(mappedByteBuffer); final LossReportReader.EntryConsumer lossEntryConsumer = mock(LossReportReader.EntryConsumer.class); LossReportReader.read(buffer, lossEntryConsumer); verify(lossEntryConsumer).accept( longThat((l) -> l > 0), longThat((l) -> l > 0), anyLong(), anyLong(), anyInt(), eq(streamId), any(), any()); } finally { IoUtil.unmap(mappedByteBuffer); } }
Example #25
Source File: MemoryMappedFileManager.java From logging-log4j2 with Apache License 2.0 | 5 votes |
protected MemoryMappedFileManager(final RandomAccessFile file, final String fileName, final OutputStream os, final boolean immediateFlush, final long position, final int regionLength, final String advertiseURI, final Layout<? extends Serializable> layout, final boolean writeHeader) throws IOException { super(os, fileName, layout, writeHeader, ByteBuffer.wrap(new byte[0])); this.immediateFlush = immediateFlush; this.randomAccessFile = Objects.requireNonNull(file, "RandomAccessFile"); this.regionLength = regionLength; this.advertiseURI = advertiseURI; this.isEndOfBatch.set(Boolean.FALSE); this.mappedBuffer = mmap(randomAccessFile.getChannel(), getFileName(), position, regionLength); this.byteBuffer = mappedBuffer; this.mappingOffset = position; }
Example #26
Source File: Utility.java From petscii-bbs with Mozilla Public License 2.0 | 5 votes |
/** * @param file * file to check * @return true if file seems to be gzipped. * @throws CbmException * if error */ public static boolean isGZipped(String file) throws CbmException { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { return GZIPInputStream.GZIP_MAGIC == (raf.read() & 0xff | ((raf.read() << 8) & 0xff00)); } catch (IOException e) { throw new CbmException("Failed to open zip header. " + e.getMessage(), e); } }
Example #27
Source File: LogFile.java From mt-flume with Apache License 2.0 | 5 votes |
protected static byte[] readDelimitedBuffer(RandomAccessFile fileHandle) throws IOException { int length = fileHandle.readInt(); Preconditions.checkState(length >= 0, Integer.toHexString(length)); byte[] buffer = new byte[length]; fileHandle.readFully(buffer); return buffer; }
Example #28
Source File: SpringBootExecutableStripper.java From reproducible-build-maven-plugin with Apache License 2.0 | 5 votes |
private byte[] extractLaunchScript(File file) throws IOException { final int startZipOffset; try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { int nextZipFileHeaderPos = 0; int matches = 0; while (matches != ZIP_FILE_HEADER.length) { int b = raf.read(); if (b == -1) { throw new IOException("Cannot extract launch script"); } if (b == ZIP_FILE_HEADER[nextZipFileHeaderPos]) { matches++; nextZipFileHeaderPos++; } else { matches = 0; nextZipFileHeaderPos = 0; } } startZipOffset = (int) raf.getFilePointer() - ZIP_FILE_HEADER.length; } final byte[] launchScript = new byte[startZipOffset]; try (FileInputStream is = new FileInputStream(file)) { is.read(launchScript); } return launchScript; }
Example #29
Source File: Installation.java From text_converter with GNU General Public License v3.0 | 5 votes |
private static String readInstallationFile(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); }
Example #30
Source File: FileLockUtil.java From oim-fx with MIT License | 5 votes |
public FileLockData(String filePath) { file = new File(filePath); try { randomAccessFile = new RandomAccessFile(file, "rw"); fileChannel = randomAccessFile.getChannel(); } catch (FileNotFoundException e) { e.printStackTrace(); } }