Java by API/java.nio/ByteBuffer
Версия от 17:43, 31 мая 2010; (обсуждение)
Содержание
- 1 ByteBuffer: allocateDirect(int size)
- 2 ByteBuffer: allocate(int capacity)
- 3 ByteBuffer: asCharBuffer()
- 4 ByteBuffer: asDoubleBuffer()
- 5 ByteBuffer: asFloatBuffer()
- 6 ByteBuffer: asLongBuffer()
- 7 ByteBuffer: asShortBuffer()
- 8 ByteBuffer: capacity()
- 9 ByteBuffer: clear()
- 10 ByteBuffer: compact()
- 11 ByteBuffer: flip()
- 12 ByteBuffer: get()
- 13 ByteBuffer: get(byte[] dst, int offset, int length)
- 14 ByteBuffer: getChar()
- 15 ByteBuffer: getDouble()
- 16 ByteBuffer: getFloat()
- 17 ByteBuffer: getInt()
- 18 ByteBuffer: get(int index)
- 19 ByteBuffer: getLong()
- 20 ByteBuffer: isDirect()
- 21 ByteBuffer: limit()
- 22 ByteBuffer: order()
- 23 ByteBuffer: order(ByteOrder bo)
- 24 ByteBuffer: position()
- 25 ByteBuffer: position(int newPosition)
- 26 ByteBuffer: put(byte b)
- 27 ByteBuffer: putChar(char ch)
- 28 ByteBuffer: putDouble(double value)
- 29 ByteBuffer: putFloat(float value)
- 30 ByteBuffer: putInt(int i)
- 31 ByteBuffer: putLong(long value)
- 32 ByteBuffer: putShort(int index, short value)
- 33 ByteBuffer: putShort(short value)
- 34 ByteBuffer: rewind()
- 35 ByteBuffer: wrap(byte[] array)
ByteBuffer: allocateDirect(int size)
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileOutputStream fileOutputStream;
FileChannel fileChannel;
ByteBuffer byteBuffer;
try {
fileOutputStream = new FileOutputStream("test.txt");
fileChannel = fileOutputStream.getChannel();
byteBuffer = ByteBuffer.allocateDirect(26);
for (int i = 0; i < 26; i++)
byteBuffer.put((byte) ("A" + i));
byteBuffer.rewind();
fileChannel.write(byteBuffer);
fileChannel.close();
fileOutputStream.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
ByteBuffer: allocate(int capacity)
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
ByteBuffer mBuf;
try {
fIn = new FileInputStream("test.txt");
fChan = fIn.getChannel();
fSize = fChan.size();
mBuf = ByteBuffer.allocate((int) fSize);
fChan.read(mBuf);
mBuf.rewind();
for (int i = 0; i < fSize; i++)
System.out.print((char) mBuf.get());
fChan.close();
fIn.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
ByteBuffer: asCharBuffer()
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class MainClass {
public static void main(String[] args) {
File aFile = new File("afile.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("\nByte buffer:");
System.out.printf("position = %2d Limit = %4d capacity = %4d%n", buf.position(), buf.limit(),
buf.capacity());
// Create a view buffer
CharBuffer charBuf = buf.asCharBuffer();
System.out.println("Char view buffer:");
System.out.printf("position = %2d Limit = %4d capacity = %4d%n", charBuf.position(), charBuf
.limit(), charBuf.capacity());
try {
outputFile.close(); // Close the O/P stream & the channel
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
ByteBuffer: asDoubleBuffer()
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
public class Main {
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, "a" });
bb.rewind();
System.out.println("Byte Buffer");
while (bb.hasRemaining())
System.out.println(bb.position() + " -> " + bb.get());
CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
System.out.println("Char Buffer");
while (cb.hasRemaining())
System.out.println(cb.position() + " -> " + cb.get());
FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
System.out.println("Float Buffer");
while (fb.hasRemaining())
System.out.println(fb.position() + " -> " + fb.get());
IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
System.out.println("Int Buffer");
while (ib.hasRemaining())
System.out.println(ib.position() + " -> " + ib.get());
LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
System.out.println("Long Buffer");
while (lb.hasRemaining())
System.out.println(lb.position() + " -> " + lb.get());
ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
System.out.println("Short Buffer");
while (sb.hasRemaining())
System.out.println(sb.position() + " -> " + sb.get());
DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();
System.out.println("Double Buffer");
while (db.hasRemaining())
System.out.println(db.position() + " -> " + db.get());
}
}
ByteBuffer: asFloatBuffer()
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
public class Main {
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, "a" });
bb.rewind();
System.out.println("Byte Buffer");
while (bb.hasRemaining())
System.out.println(bb.position() + " -> " + bb.get());
CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
System.out.println("Char Buffer");
while (cb.hasRemaining())
System.out.println(cb.position() + " -> " + cb.get());
FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
System.out.println("Float Buffer");
while (fb.hasRemaining())
System.out.println(fb.position() + " -> " + fb.get());
IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
System.out.println("Int Buffer");
while (ib.hasRemaining())
System.out.println(ib.position() + " -> " + ib.get());
LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
System.out.println("Long Buffer");
while (lb.hasRemaining())
System.out.println(lb.position() + " -> " + lb.get());
ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
System.out.println("Short Buffer");
while (sb.hasRemaining())
System.out.println(sb.position() + " -> " + sb.get());
DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();
System.out.println("Double Buffer");
while (db.hasRemaining())
System.out.println(db.position() + " -> " + db.get());
}
}
ByteBuffer: asLongBuffer()
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
File aFile = new File("file.dat");
FileInputStream inFile = null;
try {
inFile = new FileInputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(0);
}
FileChannel inChannel = inFile.getChannel();
final int COUNT = 6;
ByteBuffer buf = ByteBuffer.allocate(8 * COUNT);
long[] data = new long[COUNT];
try {
while (inChannel.read(buf) != -1) {
((ByteBuffer) (buf.flip())).asLongBuffer().get(data);
System.out.println();
for (long prime : data)
System.out.printf("%10d", prime);
buf.clear();
}
System.out.println("\nEOF reached.");
inFile.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
ByteBuffer: asShortBuffer()
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
public class Main {
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, "a" });
bb.rewind();
System.out.println("Byte Buffer");
while (bb.hasRemaining())
System.out.println(bb.position() + " -> " + bb.get());
CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
System.out.println("Char Buffer");
while (cb.hasRemaining())
System.out.println(cb.position() + " -> " + cb.get());
FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
System.out.println("Float Buffer");
while (fb.hasRemaining())
System.out.println(fb.position() + " -> " + fb.get());
IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
System.out.println("Int Buffer");
while (ib.hasRemaining())
System.out.println(ib.position() + " -> " + ib.get());
LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
System.out.println("Long Buffer");
while (lb.hasRemaining())
System.out.println(lb.position() + " -> " + lb.get());
ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();
System.out.println("Short Buffer");
while (sb.hasRemaining())
System.out.println(sb.position() + " -> " + sb.get());
DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();
System.out.println("Double Buffer");
while (db.hasRemaining())
System.out.println(db.position() + " -> " + db.get());
}
}
ByteBuffer: capacity()
/*
* Output:
File stream created successfully.
New buffer: position = 0 Limit = 1024 capacity = 1024
Buffer after loading: position = 30 Limit = 1024 capacity = 1024
Buffer after flip: position = 0 Limit = 30 capacity = 1024
Buffer contents written to file.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
String phrase = new String("www.jexp.ru\n");
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
buf.flip();
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
try {
outChannel.write(buf);
outputFile.close();
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
ByteBuffer: clear()
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) throws Exception {
String fromFileName = args[0];
String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel();
FileChannel out = new FileOutputStream(toFileName).getChannel();
ByteBuffer buff = ByteBuffer.allocate(32 * 1024);
while (in.read(buff) > 0) {
buff.flip();
out.write(buff);
buff.clear();
}
in.close();
out.close();
}
}
ByteBuffer: compact()
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] args) throws Exception{
File aFile = new File("primes.txt");
FileInputStream inFile = new FileInputStream(aFile);
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
buf.position(buf.limit());
while (true) {
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
int strLength = (int) buf.getDouble();
if (buf.remaining() < 2 * strLength) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
byte[] strChars = new byte[2 * strLength];
buf.get(strChars);
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
System.out.println(strLength);
System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
System.out.println(buf.getLong());
}
inFile.close(); }
}
ByteBuffer: flip()
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) throws Exception {
String fromFileName = args[0];
String toFileName = args[1];
FileChannel in = new FileInputStream(fromFileName).getChannel();
FileChannel out = new FileOutputStream(toFileName).getChannel();
ByteBuffer buff = ByteBuffer.allocate(32 * 1024);
while (in.read(buff) > 0) {
buff.flip();
out.write(buff);
buff.clear();
}
in.close();
out.close();
}
}
ByteBuffer: get()
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
ByteBuffer mBuf;
try {
fIn = new FileInputStream("test.txt");
fChan = fIn.getChannel();
fSize = fChan.size();
mBuf = ByteBuffer.allocate((int) fSize);
fChan.read(mBuf);
mBuf.rewind();
for (int i = 0; i < fSize; i++)
System.out.print((char) mBuf.get());
fChan.close();
fIn.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
ByteBuffer: get(byte[] dst, int offset, int length)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] bytes = new byte[10];
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.clear();
bytes = new byte[buf.capacity()];
buf.get(bytes, 0, bytes.length);
}
}
ByteBuffer: getChar()
import java.nio.ByteBuffer;
public class Main {
private static final int BSIZE = 1024;
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
bb.asCharBuffer().put("Howdy!");
char c;
while ((c = bb.getChar()) != 0)
System.out.print(c + " ");
System.out.println();
}
}
ByteBuffer: getDouble()
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] args) throws Exception{
File aFile = new File("primes.txt");
FileInputStream inFile = new FileInputStream(aFile);
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
buf.position(buf.limit());
while (true) {
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
int strLength = (int) buf.getDouble();
if (buf.remaining() < 2 * strLength) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
byte[] strChars = new byte[2 * strLength];
buf.get(strChars);
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
System.out.println(strLength);
System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
System.out.println(buf.getLong());
}
inFile.close(); }
}
ByteBuffer: getFloat()
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putFloat(12.3F);
// Reset position for reading
buf.flip();
// Retrieve the values
float f = buf.getFloat();
}
}
ByteBuffer: getInt()
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putInt(123);
// Reset position for reading
buf.flip();
// Retrieve the values
int i = buf.getInt();
}
}
ByteBuffer: get(int index)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocateDirect(10);
byte b = buf.get(5); // position=0
}
}
ByteBuffer: getLong()
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putLong(123L);
// Reset position for reading
buf.flip();
// Retrieve the values
long l = buf.getLong();
}
}
ByteBuffer: isDirect()
//Contents in a non-direct ByteBuffer are stored in the normal memory.
//Contents in a direct ByteBuffer are stored in some I/O device.
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer bbuf = ByteBuffer.wrap(new byte[10]);
boolean isDirect = bbuf.isDirect(); // false
bbuf = ByteBuffer.allocate(10);
isDirect = bbuf.isDirect(); // false
bbuf = ByteBuffer.allocateDirect(10);
isDirect = bbuf.isDirect(); // true
}
}
ByteBuffer: limit()
/*
* Output:
File stream created successfully.
New buffer: position = 0 Limit = 1024 capacity = 1024
Buffer after loading: position = 30 Limit = 1024 capacity = 1024
Buffer after flip: position = 0 Limit = 30 capacity = 1024
Buffer contents written to file.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
String phrase = new String("www.jexp.ru\n");
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
buf.flip();
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
try {
outChannel.write(buf);
outputFile.close();
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
ByteBuffer: order()
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(10);
ByteOrder order = buf.order(); // ByteOrder.BIG_ENDIAN
}
}
ByteBuffer: order(ByteOrder bo)
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
/**
* Test asCharBuffer view.
*/
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
CharBuffer charBuffer = byteBuffer.asCharBuffer();
byteBuffer.put(0, (byte) 0);
byteBuffer.put(1, (byte) "H");
byteBuffer.put(2, (byte) 0);
byteBuffer.put(3, (byte) "i");
byteBuffer.put(4, (byte) 0);
byteBuffer.put(5, (byte) "!");
byteBuffer.put(6, (byte) 0);
println(byteBuffer);
println(charBuffer);
// now slice it differently
byteBuffer.position(4);
charBuffer = byteBuffer.asCharBuffer();
println(byteBuffer);
println(charBuffer);
}
// Print info about a buffer
private static void println(Buffer buffer) {
System.out.println("pos=" + buffer.position() + ", limit=" + buffer.limit() + ", capacity="
+ buffer.capacity() + ": "" + buffer.toString() + """);
}
}
ByteBuffer: position()
/*
* Output:
File stream created successfully.
New buffer: position = 0 Limit = 1024 capacity = 1024
Buffer after loading: position = 30 Limit = 1024 capacity = 1024
Buffer after flip: position = 0 Limit = 30 capacity = 1024
Buffer contents written to file.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
String phrase = new String("www.jexp.ru\n");
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
buf.flip();
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
try {
outChannel.write(buf);
outputFile.close();
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
ByteBuffer: position(int newPosition)
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
/**
* Test asCharBuffer view.
*/
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
CharBuffer charBuffer = byteBuffer.asCharBuffer();
byteBuffer.put(0, (byte) 0);
byteBuffer.put(1, (byte) "H");
byteBuffer.put(2, (byte) 0);
byteBuffer.put(3, (byte) "i");
byteBuffer.put(4, (byte) 0);
byteBuffer.put(5, (byte) "!");
byteBuffer.put(6, (byte) 0);
println(byteBuffer);
println(charBuffer);
// now slice it differently
byteBuffer.position(4);
charBuffer = byteBuffer.asCharBuffer();
println(byteBuffer);
println(charBuffer);
}
// Print info about a buffer
private static void println(Buffer buffer) {
System.out.println("pos=" + buffer.position() + ", limit=" + buffer.limit() + ", capacity="
+ buffer.capacity() + ": "" + buffer.toString() + """);
}
}
ByteBuffer: put(byte b)
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileOutputStream fileOutputStream;
FileChannel fileChannel;
ByteBuffer byteBuffer;
try {
fileOutputStream = new FileOutputStream("test.txt");
fileChannel = fileOutputStream.getChannel();
byteBuffer = ByteBuffer.allocateDirect(26);
for (int i = 0; i < 26; i++)
byteBuffer.put((byte) ("A" + i));
byteBuffer.rewind();
fileChannel.write(byteBuffer);
fileChannel.close();
fileOutputStream.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
ByteBuffer: putChar(char ch)
/*
* Output:
File stream created successfully.
New buffer: position = 0 Limit = 1024 capacity = 1024
Buffer after loading: position = 30 Limit = 1024 capacity = 1024
Buffer after flip: position = 0 Limit = 30 capacity = 1024
Buffer contents written to file.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
String phrase = new String("www.jexp.ru\n");
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File stream created successfully.");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
buf.flip();
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
try {
outChannel.write(buf);
outputFile.close();
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
ByteBuffer: putDouble(double value)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putDouble(12.3D);
// Reset position for reading
buf.flip();
// Retrieve the values
double d = buf.getDouble();
}
}
ByteBuffer: putFloat(float value)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putFloat(12.3F);
// Reset position for reading
buf.flip();
// Retrieve the values
float f = buf.getFloat();
}
}
ByteBuffer: putInt(int i)
/*
* Output:
*/
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String[] args) {
try {
File aFile = new File("test.txt");
FileOutputStream outputFile = null;
outputFile = new FileOutputStream(aFile, true);
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(200);
buf.putInt(10).asCharBuffer().put("www.jexp.ru");
buf.position(10).flip();
outChannel.write(buf);
buf.clear();
outputFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ByteBuffer: putLong(long value)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
// Put values of different types
buf.putLong(123L);
// Reset position for reading
buf.flip();
// Retrieve the values
long l = buf.getLong();
}
}
ByteBuffer: putShort(int index, short value)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(10);
buf.putShort(0, (short) 123);
buf.get(0); // 0
buf.get(1); // 123
}
}
ByteBuffer: putShort(short value)
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] argv) throws Exception {
ByteBuffer buf = ByteBuffer.allocate(100);
buf.putShort((short) 123);
// Reset position for reading
buf.flip();
// Retrieve the values
short s = buf.getShort();
}
}
ByteBuffer: rewind()
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileInputStream fIn;
FileChannel fChan;
long fSize;
ByteBuffer mBuf;
try {
fIn = new FileInputStream("test.txt");
fChan = fIn.getChannel();
fSize = fChan.size();
mBuf = ByteBuffer.allocate((int) fSize);
fChan.read(mBuf);
mBuf.rewind();
for (int i = 0; i < fSize; i++)
System.out.print((char) mBuf.get());
fChan.close();
fIn.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
ByteBuffer: wrap(byte[] array)
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] args) throws Exception{
File aFile = new File("primes.txt");
FileInputStream inFile = new FileInputStream(aFile);
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
buf.position(buf.limit());
while (true) {
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
int strLength = (int) buf.getDouble();
if (buf.remaining() < 2 * strLength) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
byte[] strChars = new byte[2 * strLength];
buf.get(strChars);
if (buf.remaining() < 8) {
if (inChannel.read(buf.rupact()) == -1) {
break;
}
buf.flip();
}
System.out.println(strLength);
System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
System.out.println(buf.getLong());
}
inFile.close(); }
}