|
| 1 | +package btp.oneP; |
| 2 | + |
| 3 | +import java.io.FileInputStream; |
| 4 | +import java.io.FileOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.nio.ByteBuffer; |
| 7 | +import java.nio.channels.FileChannel; |
| 8 | +import java.nio.charset.Charset; |
| 9 | + |
| 10 | +public class BufferToText { |
| 11 | + private static final int BSIZE = 1024; |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + FileChannel fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 14 | + fc.write(ByteBuffer.wrap("some text".getBytes())); |
| 15 | + fc.close(); |
| 16 | + |
| 17 | + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 18 | + ByteBuffer buff = ByteBuffer.allocate(BSIZE); |
| 19 | + fc.read(buff); |
| 20 | + buff.flip(); |
| 21 | + System.out.println(buff.asCharBuffer()); |
| 22 | + buff.rewind(); |
| 23 | + |
| 24 | + String encoding = System.getProperty("file.encoding"); |
| 25 | + System.out.println("Decoded using "+encoding+":"+Charset.forName(encoding).decode(buff)); |
| 26 | + |
| 27 | + fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 28 | + fc.write(ByteBuffer.wrap("Some text".getBytes("GBK"))); |
| 29 | + fc.close(); |
| 30 | + |
| 31 | + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 32 | + buff.clear(); |
| 33 | + fc.read(buff); |
| 34 | + buff.flip(); |
| 35 | + System.out.println(buff.asCharBuffer()); |
| 36 | + System.out.println("Decoded using "+"GBK"+":"+Charset.forName("GBK").decode(buff)); |
| 37 | + |
| 38 | + fc = new FileOutputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 39 | + buff = ByteBuffer.allocate(24); |
| 40 | + buff.asCharBuffer().put("Some text!"); |
| 41 | + fc.write(buff); |
| 42 | + fc.close(); |
| 43 | + |
| 44 | + fc = new FileInputStream("C:\\Users\\dell\\Desktop\\IO\\data2.txt").getChannel(); |
| 45 | + buff.clear(); |
| 46 | + fc.read(buff); |
| 47 | + buff.flip(); |
| 48 | + System.out.println(buff.asCharBuffer()); |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments