MCPcopy Index your code
hub / github.com/BruceEckel/OnJava8-Examples / main

Method main

newio/BufferToText.java:13–86  ·  view source on GitHub ↗
(String[] args)

Source from the content-addressed store, hash-verified

11public class BufferToText {
12 private static final int BSIZE = 1024;
13 public static void main(String[] args) {
14 try(
15 FileChannel fc = new FileOutputStream(
16 "data2.txt").getChannel()
17 ) {
18 fc.write(ByteBuffer.wrap("Some text".getBytes()));
19 } catch(IOException e) {
20 throw new RuntimeException(e);
21 }
22 ByteBuffer buff = ByteBuffer.allocate(BSIZE);
23 try(
24 FileChannel fc = new FileInputStream(
25 "data2.txt").getChannel()
26 ) {
27 fc.read(buff);
28 } catch(IOException e) {
29 throw new RuntimeException(e);
30 }
31 buff.flip();
32 // Doesn't work:
33 System.out.println(buff.asCharBuffer());
34 // Decode using this system's default Charset:
35 buff.rewind();
36 String encoding =
37 System.getProperty("file.encoding");
38 System.out.println("Decoded using " +
39 encoding + ": "
40 + Charset.forName(encoding).decode(buff));
41 // Encode with something that prints:
42 try(
43 FileChannel fc = new FileOutputStream(
44 "data2.txt").getChannel()
45 ) {
46 fc.write(ByteBuffer.wrap(
47 "Some text".getBytes("UTF-16BE")));
48 } catch(IOException e) {
49 throw new RuntimeException(e);
50 }
51 // Now try reading again:
52 buff.clear();
53 try(
54 FileChannel fc = new FileInputStream(
55 "data2.txt").getChannel()
56 ) {
57 fc.read(buff);
58 } catch(IOException e) {
59 throw new RuntimeException(e);
60 }
61 buff.flip();
62 System.out.println(buff.asCharBuffer());
63 // Use a CharBuffer to write through:
64 buff = ByteBuffer.allocate(24);
65 buff.asCharBuffer().put("Some text");
66 try(
67 FileChannel fc = new FileOutputStream(
68 "data2.txt").getChannel()
69 ) {
70 fc.write(buff);

Callers

nothing calls this directly

Calls 2

readMethod · 0.45
putMethod · 0.45

Tested by

no test coverage detected