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 Project: openjdk-8-source Author: keerath File: JdpDoSomething.java License: 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 #2
Source Project: minperf Author: thomasmueller File: WikipediaTest.java License: 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 #3
Source Project: Jupiter Author: JupiterDevelopmentTeam File: BaseRegionLoader.java License: 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 #4
Source Project: Green-Creator Author: hluwa File: FileChange.java License: 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 Project: biojava Author: biojava File: TwoBitParser.java License: 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 #6
Source Project: code Author: lastwhispers File: RandomAccessFileDemo.java License: 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 #7
Source Project: J2ME-Loader Author: nikita36078 File: FileSystemFileConnection.java License: 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 #8
Source Project: tracecompass Author: tracecompass File: AbstractFileCheckpointCollection.java License: 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 #9
Source Project: quickmark Author: linmp4 File: LockPatternUtils.java License: 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 #10
Source Project: vlc-example-streamplayer Author: pedroSG94 File: VLCUtil.java License: 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 #11
Source Project: sgdtk Author: dpressel File: OverlappedTrainingRunner.java License: 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 #12
Source Project: netbeans Author: apache File: StreamUtils.java License: 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 #13
Source Project: hbase Author: apache File: FileIOEngine.java License: 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 #14
Source Project: j2objc Author: google File: OldRandomAccessFileTest.java License: 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 #15
Source Project: big-c Author: yncxcw File: NNStorage.java License: 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 #16
Source Project: xdm Author: subhra74 File: SegmentImpl.java License: 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 #17
Source Project: mt-flume Author: javachen File: TestEventQueueBackingStoreFactory.java License: 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 #18
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: JdpDoSomething.java License: 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 #19
Source Project: trekarta Author: andreynovikov File: TrackManager.java License: 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 #20
Source Project: graphicsfuzz Author: google File: PersistentFile.java License: 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 #21
Source Project: MikuMikuStudio Author: chototsu File: BufferUtil.java License: 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 #22
Source Project: gemfirexd-oss Author: gemxd File: DiskInitFile.java License: 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 #23
Source Project: j2objc Author: google File: OldRandomAccessFileTest.java License: 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 #24
Source Project: Audinaut Author: nvllsvm File: ID3v2File.java License: GNU General Public License v3.0 | 5 votes |
private HashMap parse_v3_frames(RandomAccessFile s, long payload_len) throws IOException { HashMap tags = new HashMap(); byte[] frame = new byte[10]; // a frame header is always 10 bytes long bread = 0; // total amount of read bytes while (bread < payload_len) { bread += s.read(frame); String framename = new String(frame, 0, 4); int slen = b2be32(frame, 4); /* Abort on silly sizes */ if (slen < 1 || slen > 524288) break; byte[] xpl = new byte[slen]; bread += s.read(xpl); if (framename.substring(0, 1).equals("T")) { String[] nmzInfo = normalizeTaginfo(framename, xpl); for (int i = 0; i < nmzInfo.length; i += 2) { String oggKey = nmzInfo[i]; String decPld = nmzInfo[i + 1]; if (oggKey.length() > 0 && !tags.containsKey(oggKey)) { addTagEntry(tags, oggKey, decPld); } } } } return tags; }
Example #25
Source Project: dex-method-counts Author: mihaip File: Main.java License: Apache License 2.0 | 5 votes |
RandomAccessFile openDexFile(ZipFile zipFile, ZipEntry entry) throws IOException { // We know it's a zip; see if there's anything useful inside. A // failure here results in some type of IOException (of which // ZipException is a subclass). InputStream zis = zipFile.getInputStream(entry); // Create a temp file to hold the DEX data, open it, and delete it // to ensure it doesn't hang around if we fail. File tempFile = File.createTempFile("dexdeps", ".dex"); RandomAccessFile dexFile = new RandomAccessFile(tempFile, "rw"); tempFile.delete(); // Copy all data from input stream to output file. byte copyBuf[] = new byte[32768]; int actual; while (true) { actual = zis.read(copyBuf); if (actual == -1) break; dexFile.write(copyBuf, 0, actual); } dexFile.seek(0); return dexFile; }
Example #26
Source Project: mt-flume Author: javachen File: LogFile.java License: 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 #27
Source Project: logging-log4j2 Author: apache File: MemoryMappedFileManager.java License: 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 #28
Source Project: SoftwarePilot Author: boubinjg File: MissionDriver.java License: MIT License | 5 votes |
void writeWaypoint(byte[] b) { try{ File f = new File(fname); f.delete(); MappedByteBuffer out = new RandomAccessFile(fname, "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, b.length); for(int j = 0; j<b.length; j++){ out.put(b[j]); } } catch(Exception e){ e.printStackTrace(); } }
Example #29
Source Project: swellrt Author: SwellRT File: FileDeltaCollection.java License: Apache License 2.0 | 5 votes |
/** * Create a new file delta collection for the given wavelet. * * @param waveletName name of the wavelet * @param deltaFile the file of deltas * @param index index into deltas */ public FileDeltaCollection(WaveletName waveletName, RandomAccessFile deltaFile, DeltaIndex index) { this.waveletName = waveletName; this.file = deltaFile; this.index = index; this.isOpen = true; lifeCycle.start(); }
Example #30
Source Project: phoenix Author: forcedotcom File: SpillFile.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
private static TempFile createTempFile() throws IOException { File tempFile = File.createTempFile(UUID.randomUUID().toString(), null); if (logger.isDebugEnabled()) { logger.debug("Creating new SpillFile: " + tempFile.getAbsolutePath()); } RandomAccessFile file = new RandomAccessFile(tempFile, "rw"); file.setLength(SPILL_FILE_SIZE); return new TempFile(tempFile, file); }