|
Ths Java советы иллюстрирует метод преобразования между ByteBuffer и массива байтов. Иногда разработчику необходимо данные в ByteBufer, которые будут использоваться в массиве формат. Этот совет может помочь разработчикам, чтобы решить эту проблему.
// Create a ByteBuffer from a byte array
byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// Retrieve bytes between the position and limit
bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);
// Retrieve all bytes in the buffer
buffer.clear();
bytes = new byte[buffer.capacity()];
buffer.get(bytes, 0, bytes.length);
|
|
|
Пример ниже читает файл, снизу вверх в обратный путь. Если последняя строка файла "Hello", он будет читать 'olleh. Два метода используются для реализации упомянутых выше функций.
import java.io.*;
import java.nio.channels.*;
import java.nio.*;
public class FileReaderDownToUp {
public static void main(String[] args) {
try {
//method 1
File f = new File("hello.txt");
FileReader fr = new FileReader(f);
char[] c = new char[(int)f.length()];
char[] cnew = new char[(int)f.length()];
StringBuffer sbuf = new StringBuffer();
fr.read(c,0,(int)f.length());
int len = (int)f.length();
for (int i = 0, j = len - 1; i < len ; i++, j--) {
cnew[i] = c[j];
sbuf.append(cnew[i]);
}
System.out.println(sbuf.toString());
fr.close();
//method 2
/*
RandomAccessFile f = new RandomAccessFile("hello.txt","rw");
FileChannel fc = f.getChannel();
// map file to buffer
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,
0, f.length());
int len = (int)f.length();
for (int i = 0, j = len - 1; i < j; i++, j--)
{
byte b = mbb.get(i);
mbb.put(i, mbb.get(j));
mbb.put(j, b);
}
// finish up
fc.close();
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|
|
Ths Java советы иллюстрирует способ создания отображаемых в памяти файлов. ByteArray может быть создан в то время как отображение файла в памяти. ByteBuffer имеет потенциал, который определяет, сколько байт она содержит. Этот потенциал не может измениться. Дальнейшее байт ByteArray может быть восстановлена с помощью получить ().
try {
File file = new File("filename");
// Create a read-only memory-mapped file
FileChannel roChannel =
new RandomAccessFile(file, "r").getChannel();
ByteBuffer readonlybuffer =
roChannel.map(FileChannel.MapMode.READ_ONLY,
0, (int)roChannel.size());
// Create a read-write memory-mapped file
FileChannel rwChannel =
new RandomAccessFile(file, "rw").getChannel();
ByteBuffer writeonlybuffer=
rwChannel.map(FileChannel.MapMode.READ_WRITE,
0, (int)rwChannel.size());
// Create a private (copy-on-write) memory-mapped file.
// Any write to this channel results in a private
// copy of the data.
FileChannel pvChannel =
new RandomAccessFile(file, "rw").getChannel();
ByteBuffer privatebuffer =
roChannel.map(FileChannel.MapMode.READ_WRITE,
0, (int)rwChannel.size());
} catch (IOException e) {
}
|
|
|
Это Java советы иллюстрирует метод чтения из канала с ByteBuffer. Разработчик может использовать ByteBuffer для чтения из канала. Tricky частью этой операции является помню правильно определить позицию буфера, до и после чтения.
try {
// Obtain a channel
ReadableByteChannel channel =
new FileInputStream("infile").getChannel();
// Create a direct ByteBuffer; see also e158 Creating a ByteBuffer
ByteBuffer buf = ByteBuffer.allocateDirect(10);
int numRead = 0;
while (numRead >= 0) {
// read() places read bytes at the buffer's position so the
// position should always be properly set before calling read()
// This method sets the position to 0
buf.rewind();
// Read bytes from the channel
numRead = channel.read(buf);
// The read() method also moves the position so in order to
// read the new bytes, the buffer's position must be
// set back to 0
buf.rewind();
// Read bytes from ByteBuffer; see also
// e159 Getting Bytes from a ByteBuffer
for (int i=0; i<numRead; i++) {
byte b = buf.get();
}
}
} catch (Exception e) {
}
|
|
|
Этот совет Java демонстрирует метод получения байта из ByteBuffer. ByteBuffer имеет потенциал, который определяет, сколько байт она содержит. Этот потенциал не может измениться. Байт ByteBuffer также можно извлечь с помощью относительного версия получить (), которая использует положения и предельных свойствах буфера. В частности, эта версия получить () возвращает байт на позицию и выдвигает позицию за другой. получить () не может получить байт прошлого предела (хотя предел может быть меньше мощности). Положение всегда <\u003d предел и предел всегда <\u003d потенциал.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Retrieve the capacity of the ByteBuffer
int capacity = bbuf.capacity(); // 10
// The position is not affected by the absolute get() method.
byte b = bbuf.get(5); // position=0
// Set the position
bbuf.position(5);
// Use the relative get()
b = bbuf.get();
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
|
|
|
Этот совет Java демонстрирует способ создания ByteBuffer. Фиксированная bufferes потенциал, который проведет байтовые значения известны как ByteBuffer. Там могут быть различные способы создания ByteBuffer.
// Create a ByteBuffer using a byte array
byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// Create a non-direct ByteBuffer with a 10 byte capacity
// The underlying storage is a byte array.
buffer = ByteBuffer.allocate(10);
// Create a memory-mapped ByteBuffer with a 10 byte capacity.
buffer = ByteBuffer.allocateDirect(10);
|
|
|
Это Java советы иллюстрирует способ создания файла блокировки файлов. Разработчик может отметить, что блокировка файла могут зависеть от платформы. На некоторых платформах, блокирующий файл консультативным, а это значит, что если приложение проверяет наличие файла блокировки, он не будет препятствовать доступу к файлу. На других платформах, блокировка файла является обязательным, это означает, что файл блокировки предотвращает любые приложения с доступом к файлу.
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel =
new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Remember to release the lock
lock.release();
// Close the file
channel.close();
} catch (Exception e) {
}
|
|
|
Это Java советы иллюстрирует метод записи на канал с ByteBuffer. Разработчик может использовать ByteBuffer для записи в канал. Выходного потока используется для записи на канал. Хитрая часть этой операции заключается в помню правильно определить позицию буфера, до и после записи.
try {
// Obtain a channel
WritableByteChannel channel =
new FileOutputStream("outfilename").getChannel();
// Create a direct ByteBuffer;
ByteBuffer buffer = ByteBuffer.allocateDirect(10);
byte[] bytes = new byte[1024];
int count = 0;
int index = 0;
// Continue writing bytes until there are no more
while (count >= 0) {
if (index == count) {
count = inputStream.read(bytes);
index = 0;
}
// Fill ByteBuffer
while (index < count && buffer.hasRemaining()) {
buffer.put(bytes[index++]);
}
// Set the limit to the current position and
// the position to 0 making the new bytes
// visible for write()
buffer.flip();
// Write the bytes to the channel
int numWritten = channel.write(buffer);
// Check if all bytes were written
if (buf.hasRemaining()) {
// If not all bytes were written, move the unwritten bytes
// to the beginning and set position just after the last
// unwritten byte; also set limit to the capacity
buffer.compact();
} else {
// Set the position to 0 and the limit to capacity
buffer.clear();
}
}
// Close the file
channel.close();
} catch (Exception e) {
}
|
|
|
Этот совет Java демонстрирует метод ввода байтов в ByteBuffer. ByteBuffer имеет потенциал, который определяет, сколько байт она contains.The байт ByteBuffer также может быть установлен с помощью относительного версия оферте (), которая использует положения и предельных свойствах буфера. В частности, эта версия оферте () устанавливает байт на позицию и выдвигает позицию за другой. положить () не может установить байт прошлого предела (хотя предел может быть меньше мощности). Положение всегда <\u003d предел и предел всегда <\u003d потенциал.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Retrieve the capacity of the ByteBuffer
int capacity = bbuf.capacity(); // 10
// Use the absolute put().
// This method does not affect the position.
bbuf.put((byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put()
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
|
|
|
Это Java советы иллюстрирует метод копирования одного файла в другой файл через канал. Канал создается как от источника, а также назначения и затем файл копируется между этими двумя каналами.
try {
// Create channel on the source
FileChannel srcChannel =
new FileInputStream("srcFilename").getChannel();
// Create channel on the destination
FileChannel dstChannel =
new FileOutputStream("dstFilename").getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}
|
|