1.字节与字符的演变
public class inputStream { public static void test1() throws Exception{ File file= new File("D:\log.txt"); //从文件中读取消息 FileInputStream inputStream =new FileInputStream(file); System.out.println(inputStream.getChannel()); //决定是否使用缓存 BufferedInputStream stream=new BufferedInputStream(inputStream); //filterInputStream的一种,控制特定输入流和输出流 DataInputStream in =new DataInputStream(inputStream); FileOutputStream outputStream =new FileOutputStream(file); BufferedOutputStream stream1=new BufferedOutputStream(outputStream,1024); DataOutputStream out =new DataOutputStream(stream1); //只能是英文或者数字 out.writeBytes("hello world!"); out.close(); while(in.available()!=0){ System.out.print((char)in.readByte()); } in.close(); } public static void test2() throws Exception{ File file=new File("D:\log.txt"); FileInputStream inputStream =new FileInputStream(file); InputStreamReader streamReader =new InputStreamReader(inputStream); BufferedReader reader =new BufferedReader(streamReader); FileOutputStream outputStream =new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(outputStream); writer.write("哈哈"); writer.close(); while (reader.ready()){ System.out.print(reader.read()); } reader.close(); } public static void main(String[] args){ try { test2(); } catch (Exception e) { e.printStackTrace(); } } }
有一点很清楚,无论我们何时使用readline(),都不应该使用DataInputStream,而应该使用BufferedReader,除了这一点,DataInputStream仍然是I/O类库的首选成员。
2.通道与缓冲之间的秘密
/** * 通道以原始的字节形式或者基本数据类型输出和读取数据 * 没办法输出或者读取对象,即使是字符串对象也不行 * * NIO的方法主要是将数据以ByteBuffer的形式写入到文件,一块一块的写,就快了好多。 */ public class Channels { private final static int SIZE=1024; public static void main(String[] args)throws IOException{ FileChannel fc =new FileOutputStream("D:\log.txt").getChannel(); //wrap()函数是用于将数组包装在ByteBuffer中 fc.write(ByteBuffer.wrap("some test!".getBytes())); fc.close(); fc=new RandomAccessFile("D:\log.txt","rw").getChannel(); //把通道随处移动到fc的末尾,进行数据追加 fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more!".getBytes())); fc.close(); fc=new FileInputStream("D:\log.txt").getChannel(); //分配缓存 ByteBuffer buffer = ByteBuffer.allocate(SIZE); //往缓存中写东西 fc.read(buffer); //做好让别人读取字节的准备 buffer.flip(); while(buffer.hasRemaining()){ System.out.print((char)buffer.get()); } } }
如果把通道当作一个煤矿,则ByteBuffer则是去煤矿的唯一小车,ByteBuffer装成一块一块的,去读或者写。