2015-11-03 12:00:44 -08:00
|
|
|
// newio/BufferToText.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// Converting text to and from ByteBuffers
|
|
|
|
import java.nio.*;
|
|
|
|
import java.nio.channels.*;
|
|
|
|
import java.nio.charset.*;
|
|
|
|
import java.io.*;
|
|
|
|
|
|
|
|
public class BufferToText {
|
|
|
|
private static final int BSIZE = 1024;
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
|
|
|
try(FileChannel fc = new FileOutputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.write(ByteBuffer.wrap("Some text".getBytes()));
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
|
2016-01-25 18:05:55 -08:00
|
|
|
try(FileChannel fc = new FileInputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.read(buff);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
buff.flip();
|
|
|
|
// Doesn't work:
|
|
|
|
System.out.println(buff.asCharBuffer());
|
|
|
|
// Decode using this system's default Charset:
|
|
|
|
buff.rewind();
|
|
|
|
String encoding = System.getProperty("file.encoding");
|
|
|
|
System.out.println("Decoded using " + encoding + ": "
|
|
|
|
+ Charset.forName(encoding).decode(buff));
|
|
|
|
// Or, we could encode with something that prints:
|
2016-01-25 18:05:55 -08:00
|
|
|
try(FileChannel fc = new FileOutputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.write(ByteBuffer.wrap(
|
|
|
|
"Some text".getBytes("UTF-16BE")));
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
// Now try reading again:
|
|
|
|
buff.clear();
|
2016-01-25 18:05:55 -08:00
|
|
|
try(FileChannel fc = new FileInputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.read(buff);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
buff.flip();
|
|
|
|
System.out.println(buff.asCharBuffer());
|
|
|
|
// Use a CharBuffer to write through:
|
|
|
|
buff = ByteBuffer.allocate(24); // More than needed
|
|
|
|
buff.asCharBuffer().put("Some text");
|
2016-01-25 18:05:55 -08:00
|
|
|
try(FileChannel fc = new FileOutputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.write(buff);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
// Read and display:
|
|
|
|
buff.clear();
|
2016-01-25 18:05:55 -08:00
|
|
|
try(FileChannel fc = new FileInputStream(
|
|
|
|
"data2.txt").getChannel()) {
|
|
|
|
fc.read(buff);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
buff.flip();
|
|
|
|
System.out.println(buff.asCharBuffer());
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
????
|
2016-07-22 14:45:35 -06:00
|
|
|
Decoded using windows-1252: Some text
|
2015-06-15 17:47:35 -07:00
|
|
|
Some text
|
|
|
|
Some textNULNULNUL
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|