本文整理匯總了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();
}
}
示例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);
}
示例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;
}
示例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);
}
}
}
示例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;
}
}
示例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();
}
示例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);
}
}
示例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;
}
示例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();
}
示例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();
}
}
示例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;
}
示例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;
}
}
示例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);
}
}
示例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);
}
示例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;
}
}