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

Method main

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

Source from the content-addressed store, hash-verified

11 private static String name = "data.txt";
12 private static final int BSIZE = 1024;
13 public static void main(String[] args) {
14 // Write a file:
15 try(
16 FileChannel fc = new FileOutputStream(name)
17 .getChannel()
18 ) {
19 fc.write(ByteBuffer
20 .wrap("Some text ".getBytes()));
21 } catch(IOException e) {
22 throw new RuntimeException(e);
23 }
24 // Add to the end of the file:
25 try(
26 FileChannel fc = new RandomAccessFile(
27 name, "rw").getChannel()
28 ) {
29 fc.position(fc.size()); // Move to the end
30 fc.write(ByteBuffer
31 .wrap("Some more".getBytes()));
32 } catch(IOException e) {
33 throw new RuntimeException(e);
34 }
35 // Read the file:
36 try(
37 FileChannel fc = new FileInputStream(name)
38 .getChannel()
39 ) {
40 ByteBuffer buff = ByteBuffer.allocate(BSIZE);
41 fc.read(buff);
42 buff.flip();
43 while(buff.hasRemaining())
44 System.out.write(buff.get());
45 } catch(IOException e) {
46 throw new RuntimeException(e);
47 }
48 System.out.flush();
49 }
50}
51/* Output:
52Some text Some more

Callers

nothing calls this directly

Calls 3

getMethod · 0.65
sizeMethod · 0.45
readMethod · 0.45

Tested by

no test coverage detected