Java Reference
In-Depth Information
LISTING 17.4
The Full Text of BufferConverter.java
1: import java.nio.*;
2: import java.nio.channels.*;
3: import java.nio.charset.*;
4: import java.io.*;
5:
6: public class BufferConverter {
7: public static void main(String[] arguments) {
8: try {
9: // read byte data into a byte buffer
10: String data = “friends.dat”;
11: FileInputStream inData = new FileInputStream(data);
12: FileChannel inChannel = inData.getChannel();
13: long inSize = inChannel.size();
14: ByteBuffer source = ByteBuffer.allocate( (int)inSize );
15: inChannel.read(source, 0);
16: source.position(0);
17: System.out.println(“Original byte data:”);
18: for (int i = 0; source.remaining() > 0; i++)
19: System.out.print(source.get() + “ “);
20:
21: // convert byte data into character data
22: source.position(0);
23: Charset ascii = Charset.forName(“US-ASCII”);
24: CharsetDecoder toAscii = ascii.newDecoder();
25: CharBuffer destination = toAscii.decode(source);
26: destination.position(0);
27: System.out.println(“\n\nNew character data:”);
28: for (int i = 0; destination.remaining() > 0; i++)
29: System.out.print(destination.get());
30: } catch (FileNotFoundException fne) {
31: System.out.println(fne.getMessage());
32: } catch (IOException ioe) {
33: System.out.println(ioe.getMessage());
34: }
35: }
36: }
17
After you compile the file, you need a copy of friends.dat , the small file of byte data
used in the application. To download it from the topic's website at http://www.
java21days.com, open the Day 17 page, click the friends.dat hyperlink, and save the
file in the same place as BufferConverter.class .
TIP
You also can create your own file. Open a text editor, type a sen-
tence or two in the document, and save it as friends.dat .
 
Search WWH ::




Custom Search