下面列出了java.nio.channels.OverlappingFileLockException#java.io.RandomAccessFile 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
}
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);
}
}
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();
}
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);
}
}
@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);
}
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();
}
};
}
/**
* 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;
}
/**
* 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;
}
}
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;
}
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();
}
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);
}
}
}
}
@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();
}
}
/**
* 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.
}
}
@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;
}
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();
}
@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();
}
}
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();
}
}
/**
* 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);
}
@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;
}
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);
}
}
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);
}
}
/**
* 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.
}
}
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;
}
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;
}
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;
}
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;
}
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();
}
}
/**
* 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();
}
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);
}
/**
* Read big header
*
* @param br The randomAccessFile
* @param isSequential If is sequential
* @return The big header
* @throws IOException
*/
public BigHeader readBigHeader(RandomAccessFile br, boolean isSequential) throws IOException {
BigHeader bh = new BigHeader();
if (isSequential) {
br.skipBytes(4);
}
byte[] bytes = new byte[80];
int i, j;
for (i = 0; i < 20; i++) {
for (j = 0; j < 50; j++) {
bh.bhi[j][i] = br.readInt();
}
}
for (i = 0; i < 20; i++) {
for (j = 0; j < 20; j++) {
bh.bhr[j][i] = br.readFloat();
}
}
for (i = 0; i < 20; i++) {
for (j = 0; j < 50; j++) {
br.read(bytes);
bh.bhic[j][i] = new String(bytes).trim();
}
}
for (i = 0; i < 20; i++) {
for (j = 0; j < 20; j++) {
br.read(bytes);
bh.bhrc[j][i] = new String(bytes).trim();
}
}
if (isSequential) {
br.skipBytes(4);
}
return bh;
}