-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBufferToText.java
More file actions
67 lines (56 loc) · 1.83 KB
/
BufferToText.java
File metadata and controls
67 lines (56 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package io;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.io.*;
import java.util.*;
/**
* RUN:
* javac io/BufferToText.java && java io.BufferToText
*
* OUTPUT:
* ?????
* Decoded in Cp1251: Some text
* Some text
* Some text
*/
public class BufferToText {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
// 1
FileChannel fc = new FileOutputStream("data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
fc = new FileInputStream("data2.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
fc.read(buffer);
buffer.flip();
System.out.println(buffer.asCharBuffer()); // show incorrect text: ?????
// decode with default codepage
buffer.rewind();
String encoding = System.getProperty("file.encoding");
System.out.println("Decoded in " + encoding + ": "
+ Charset.forName(encoding).decode(buffer)
);
// 2
fc = new FileOutputStream("data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes("UTF-16BE")));
fc.close();
fc = new FileInputStream("data2.txt").getChannel();
buffer.clear();
fc.read(buffer);
buffer.flip();
System.out.println(buffer.asCharBuffer());
// 3
fc = new FileOutputStream("data2.txt").getChannel();
buffer = ByteBuffer.allocate(30);
buffer.asCharBuffer().put("Some text");
fc.write(buffer);
fc.close();
fc = new FileInputStream("data2.txt").getChannel();
buffer.clear();
fc.read(buffer);
buffer.flip();
System.out.println(buffer.asCharBuffer());
}
}