当前位置: 首页>>代码示例>>Java>>正文


Java RandomAccessFile.getChannel方法代码示例

本文整理汇总了Java中java.io.RandomAccessFile.getChannel方法的典型用法代码示例。如果您正苦于以下问题:Java RandomAccessFile.getChannel方法的具体用法?Java RandomAccessFile.getChannel怎么用?Java RandomAccessFile.getChannel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.io.RandomAccessFile的用法示例。


在下文中一共展示了RandomAccessFile.getChannel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: truncateFileAtURL

import java.io.RandomAccessFile; //导入方法依赖的package包/类
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
开发者ID:rodrigonsh,项目名称:alerta-fraude,代码行数:24,代码来源:LocalFilesystem.java

示例2: read

import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
 * Creates a relay that reads a recorded stream from {@code file}.
 *
 * <p><strong>Warning:</strong> callers to this method must immediately call {@link #newSource} to
 * create a source and close that when they're done. Otherwise a handle to {@code file} will be
 * leaked.
 */
public static Relay read(File file) throws IOException {
  RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  FileOperator fileOperator = new FileOperator(randomAccessFile.getChannel());

  // Read the header.
  Buffer header = new Buffer();
  fileOperator.read(0, header, FILE_HEADER_SIZE);
  ByteString prefix = header.readByteString(PREFIX_CLEAN.size());
  if (!prefix.equals(PREFIX_CLEAN)) throw new IOException("unreadable cache file");
  long upstreamSize = header.readLong();
  long metadataSize = header.readLong();

  // Read the metadata.
  Buffer metadataBuffer = new Buffer();
  fileOperator.read(FILE_HEADER_SIZE + upstreamSize, metadataBuffer, metadataSize);
  ByteString metadata = metadataBuffer.readByteString();

  // Return the result.
  return new Relay(randomAccessFile, null, upstreamSize, metadata, 0L);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:28,代码来源:Relay.java

示例3: call

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public ByteBuffer call() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    buff = ByteBuffer.allocate(bufferSize);
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    while (!stop.isLocked()) {
        RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.read(buff);
        FileChannel channel = temp.getChannel();
        channel.write(buff);
        if (!pause.isLocked()) {
            MappedByteBuffer b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
            b.clear();
        }
        temp.close();
        buff.clear();
    }

    return null;
}
 
开发者ID:EventHorizon27,项目名称:dataset-lib,代码行数:21,代码来源:StreamThread.java

示例4: storeSession

import java.io.RandomAccessFile; //导入方法依赖的package包/类
@Override
public void storeSession(@NonNull SignalProtocolAddress address, @NonNull SessionRecord record) {
  synchronized (FILE_LOCK) {
    try {
      RandomAccessFile sessionFile  = new RandomAccessFile(getSessionFile(address), "rw");
      FileChannel      out          = sessionFile.getChannel();

      out.position(0);
      writeInteger(CURRENT_VERSION, out);
      writeBlob(record.serialize(), out);
      out.truncate(out.position());

      sessionFile.close();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }
}
 
开发者ID:CableIM,项目名称:Cable-Android,代码行数:19,代码来源:TextSecureSessionStore.java

示例5: LockExclusive

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public boolean LockExclusive(File targetFile) {

            if (targetFile == null) {
                return false;
            }
            try {
                File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
                if (!lockFile.exists()) {
                    lockFile.createNewFile();
                }
                RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
                FileChannel channel = randomAccessFile.getChannel();
                java.nio.channels.FileLock lock = channel.lock();
                if (!lock.isValid()) {
                    return false;
                }
                RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
 
开发者ID:coding-dream,项目名称:TPlayer,代码行数:23,代码来源:FileUtils.java

示例6: fileChannelExa

import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
 * FileChannel 负责文件的读写
 * @throws IOException
 */
public void fileChannelExa() throws IOException {

    String filePath = BasicChannelExample.class.getClassLoader().getResource("data/nio-data.txt").getFile();
    RandomAccessFile aFile = new RandomAccessFile(filePath , "rw");

    FileChannel inChannel = aFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(48);

    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {

        System.out.println("Read " + bytesRead);
        buf.flip();

        while(buf.hasRemaining()){
            System.out.print((char) buf.get());
        }

        buf.clear();
        bytesRead = inChannel.read(buf);
    }
    aFile.close();
}
 
开发者ID:laidu,项目名称:java-learn,代码行数:29,代码来源:BasicChannelExample.java

示例7: uploadFileByMappedByteBuffer

import java.io.RandomAccessFile; //导入方法依赖的package包/类
@Override
public void uploadFileByMappedByteBuffer(MultipartFileParam param) throws IOException {
    String fileName = param.getName();
    String uploadDirPath = finalDirPath + param.getMd5();
    String tempFileName = fileName + "_tmp";
    File tmpDir = new File(uploadDirPath);
    File tmpFile = new File(uploadDirPath, tempFileName);
    if (!tmpDir.exists()) {
        tmpDir.mkdirs();
    }

    RandomAccessFile tempRaf = new RandomAccessFile(tmpFile, "rw");
    FileChannel fileChannel = tempRaf.getChannel();

    //写入该分片数据
    long offset = CHUNK_SIZE * param.getChunk();
    byte[] fileData = param.getFile().getBytes();
    MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, offset, fileData.length);
    mappedByteBuffer.put(fileData);
    // 释放
    FileMD5Util.freedMappedByteBuffer(mappedByteBuffer);
    fileChannel.close();

    boolean isOk = checkAndSetUploadProgress(param, uploadDirPath);
    if (isOk) {
        boolean flag = renameFile(tmpFile, fileName);
        System.out.println("upload complete !!" + flag + " name=" + fileName);
    }
}
 
开发者ID:Fourwenwen,项目名称:Breakpoint-http,代码行数:30,代码来源:StorageServiceImpl.java

示例8: RandomAccessFileDataSink

import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
 * Constructs a new {@code RandomAccessFileDataSink} which stores output starting from the
 * specified position of the provided file.
 */
public RandomAccessFileDataSink(RandomAccessFile file, long startPosition) {
    if (file == null) {
        throw new NullPointerException("file == null");
    }
    if (startPosition < 0) {
        throw new IllegalArgumentException("startPosition: " + startPosition);
    }
    mFile = file;
    mFileChannel = file.getChannel();
    mPosition = startPosition;
}
 
开发者ID:F8LEFT,项目名称:FApkSigner,代码行数:16,代码来源:RandomAccessFileDataSink.java

示例9: LongMemoryMappedData

import java.io.RandomAccessFile; //导入方法依赖的package包/类
LongMemoryMappedData(RandomAccessFile file, long length)
          throws IOException {
    FileChannel channel = file.getChannel();
    dumpBuffer = new MappedByteBuffer[(int) (((length + BUFFER_SIZE) - 1) / BUFFER_SIZE)];

    for (int i = 0; i < dumpBuffer.length; i++) {
        long position = i * BUFFER_SIZE;
        long size = Math.min(BUFFER_SIZE + BUFFER_EXT, length - position);
        dumpBuffer[i] = channel.map(MemoryMappedData.MAP_MODE, position, size);
    }

    channel.close();
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:14,代码来源:AbstractLongMap.java

示例10: wipeFile

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public static void wipeFile(String file2wipe) throws IOException, FileNotFoundException
{
	File f2w = new File(file2wipe);
	
	 if (f2w.exists())
	 {
		
		SecureRandom sr = new SecureRandom();
		RandomAccessFile raf = new RandomAccessFile(f2w, "rw");
		FileChannel channel = raf.getChannel();
		MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
		
		while (buffer.hasRemaining())
		{
			buffer.put((byte) 0);
		}
		buffer.force();
		buffer.rewind();
		
		while (buffer.hasRemaining())
		{
		    buffer.put((byte) 0xFF);
		}
		buffer.force();
		buffer.rewind();
		
		byte[] data = new byte[1];
		while (buffer.hasRemaining())
		{
		    sr.nextBytes(data);
		    buffer.put(data[0]);
		}
		buffer.force();
	    raf.close();
		f2w.delete(); 
	 }
}
 
开发者ID:MonroCoury,项目名称:CryptoKnight,代码行数:38,代码来源:FileEncrypt.java

示例11: FileNio

import java.io.RandomAccessFile; //导入方法依赖的package包/类
FileNio(String fileName, String mode) throws IOException {
    this.name = fileName;
    RandomAccessFile file = new RandomAccessFile(fileName, mode);
    this.channel = file.getChannel();
    this.fileLength = DbleServer.getInstance().getConfig().getSystem().getMappedFileSize();
    this.pos = 0;
}
 
开发者ID:actiontech,项目名称:dble,代码行数:8,代码来源:FileNio.java

示例12: LogOutputStream

import java.io.RandomAccessFile; //导入方法依赖的package包/类
public LogOutputStream(File file, boolean append, long segmentMaxSize,
    long preallocatedSize, int bufferSize)
    throws IOException {
  this.file = file;
  this.checksum = new PureJavaCrc32C();
  this.segmentMaxSize = segmentMaxSize;
  this.preallocatedSize = preallocatedSize;
  RandomAccessFile rp = new RandomAccessFile(file, "rw");
  fc = rp.getChannel();
  fc.position(fc.size());
  preallocatedPos = fc.size();
  out = new BufferedWriteChannel(fc, bufferSize);

  try {
    fc = rp.getChannel();
    fc.position(fc.size());
    preallocatedPos = fc.size();

    out = new BufferedWriteChannel(fc, bufferSize);
    if (!append) {
      create();
    }
  } catch (IOException ioe) {
    LOG.warn("Hit IOException while creating log segment " + file
        + ", delete the partial file.");
    // hit IOException, clean up the in-progress log file
    try {
      FileUtils.deleteFully(file);
    } catch (IOException e) {
      LOG.warn("Failed to delete the file " + file, e);
    }
    throw ioe;
  }
}
 
开发者ID:apache,项目名称:incubator-ratis,代码行数:35,代码来源:LogOutputStream.java

示例13: getDirectWritableChannel

import java.io.RandomAccessFile; //导入方法依赖的package包/类
@Override
protected WritableByteChannel getDirectWritableChannel() throws ContentIOException
{
    try
    {
        // we may not write to an existing file - EVER!!
        if (file.exists() && file.length() > 0)
        {
            throw new IOException("File exists - overwriting not allowed");
        }
        // create the channel
        WritableByteChannel channel = null;
        if (allowRandomAccess)
        {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");  // will create it
            channel = randomAccessFile.getChannel();
        }
        else
        {
            OutputStream os = new FileOutputStream(file);
            channel = Channels.newChannel(os);
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug("Opened write channel to file: \n" +
                    "   file: " + file + "\n" +
                    "   random-access: " + allowRandomAccess);
        }
        return channel;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:37,代码来源:FileContentWriter.java

示例14: readFile

import java.io.RandomAccessFile; //导入方法依赖的package包/类
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
		String fileName) {
	StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {

		@Override
		public void writeTo(OutputStream outputStream) {
			try {

				String fileStr = fileLocation + File.separator + imageDir + File.separator + id + File.separator
						+ fileName;

				RandomAccessFile file = new RandomAccessFile(fileStr, "r");
				FileChannel inChannel = file.getChannel();
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				while (inChannel.read(buffer) > 0) {
					buffer.flip();
					for (int i = 0; i < buffer.limit(); i++) {
						outputStream.write(buffer.get());
					}
					buffer.clear();
					outputStream.flush();
				}
				inChannel.close();
				file.close();

			} catch (IOException e) {
				logger.error("Image Not Found : error " + e.getMessage());
				throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
			}
		}
	};

	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
	return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
 
开发者ID:quebic-source,项目名称:microservices-sample-project,代码行数:38,代码来源:LocalStorageImageUtil.java

示例15: serializeAndWrite

import java.io.RandomAccessFile; //导入方法依赖的package包/类
/**
 * Serialize the set of in flights into a byte longBuffer.
 *
 * @return Returns the checksum of the buffer that is being
 * asynchronously written to disk.
 */
public void serializeAndWrite() throws Exception {
  Collection<Long> values = inflightEvents.values();
  if (!fileChannel.isOpen()) {
    file = new RandomAccessFile(inflightEventsFile, "rw");
    fileChannel = file.getChannel();
  }
  if (values.isEmpty()) {
    file.setLength(0L);
  }
  //What is written out?
  //Checksum - 16 bytes
  //and then each key-value pair from the map:
  //transactionid numberofeventsforthistxn listofeventpointers

  try {
    int expectedFileSize = (((inflightEvents.keySet().size() * 2) //for transactionIDs and
                                                                  //events per txn ID
        + values.size()) * 8) //Event pointers
        + 16; //Checksum
    //There is no real need of filling the channel with 0s, since we
    //will write the exact number of bytes as expected file size.
    file.setLength(expectedFileSize);
    Preconditions.checkState(file.length() == expectedFileSize,
        "Expected File size of inflight events file does not match the "
            + "current file size. Checkpoint is incomplete.");
    file.seek(0);
    final ByteBuffer buffer = ByteBuffer.allocate(expectedFileSize);
    LongBuffer longBuffer = buffer.asLongBuffer();
    for (Long txnID : inflightEvents.keySet()) {
      Set<Long> pointers = inflightEvents.get(txnID);
      longBuffer.put(txnID);
      longBuffer.put((long) pointers.size());
      LOG.debug("Number of events inserted into "
          + "inflights file: " + String.valueOf(pointers.size())
          + " file: " + inflightEventsFile.getCanonicalPath());
      long[] written = ArrayUtils.toPrimitive(
          pointers.toArray(new Long[0]));
      longBuffer.put(written);
    }
    byte[] checksum = digest.digest(buffer.array());
    file.write(checksum);
    buffer.position(0);
    fileChannel.write(buffer);
    fileChannel.force(true);
    syncRequired = false;
  } catch (IOException ex) {
    LOG.error("Error while writing checkpoint to disk.", ex);
    throw ex;
  }
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:57,代码来源:FlumeEventQueue.java


注:本文中的java.io.RandomAccessFile.getChannel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。