java.nio.channels.OverlappingFileLockException#java.io.RandomAccessFile源码实例Demo

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

源代码1 项目: openjdk-8-source   文件: JdpDoSomething.java
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();
    }
}
 
源代码2 项目: Jupiter   文件: BaseRegionLoader.java
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);
    }

}
 
源代码3 项目: Green-Creator   文件: FileChange.java
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();
}
 
源代码4 项目: biojava   文件: TwoBitParser.java
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);
	}
}
 
源代码5 项目: code   文件: RandomAccessFileDemo.java
@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);
}
 
源代码6 项目: J2ME-Loader   文件: FileSystemFileConnection.java
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;
}
 
源代码8 项目: quickmark   文件: LockPatternUtils.java
/**
 * 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;
	}
}
 
源代码9 项目: vlc-example-streamplayer   文件: VLCUtil.java
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;
}
 
源代码10 项目: sgdtk   文件: OverlappedTrainingRunner.java
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();

}
 
源代码11 项目: netbeans   文件: StreamUtils.java
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);
            }
        }
    }
}
 
源代码12 项目: hbase   文件: FileIOEngine.java
@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();
  }
}
 
源代码13 项目: j2objc   文件: OldRandomAccessFileTest.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(), 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.
    }

}
 
源代码14 项目: big-c   文件: NNStorage.java
@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;
}
 
源代码15 项目: xdm   文件: SegmentImpl.java
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();
  }
}
 
源代码17 项目: openjdk-jdk8u   文件: JdpDoSomething.java
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();
    }
}
 
源代码18 项目: trekarta   文件: TrackManager.java
/**
 * 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);
}
 
源代码19 项目: graphicsfuzz   文件: PersistentFile.java
@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;
}
 
源代码20 项目: MikuMikuStudio   文件: BufferUtil.java
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);
    }
}
 
源代码21 项目: gemfirexd-oss   文件: DiskInitFile.java
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);
  }
}
 
源代码22 项目: j2objc   文件: OldRandomAccessFileTest.java
/**
 * 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.
    }
}
 
源代码23 项目: Audinaut   文件: ID3v2File.java
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;
}
 
源代码24 项目: dex-method-counts   文件: Main.java
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;
}
 
源代码25 项目: mt-flume   文件: LogFile.java
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;
}
 
源代码26 项目: logging-log4j2   文件: MemoryMappedFileManager.java
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;
}
 
源代码27 项目: SoftwarePilot   文件: MissionDriver.java
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();
   }
  	}
 
源代码28 项目: swellrt   文件: FileDeltaCollection.java
/**
 * 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();
}
 
源代码29 项目: phoenix   文件: SpillFile.java
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);
}
 
源代码30 项目: MeteoInfo   文件: MM5DataInfo.java
/**
 * 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;
}