io包是以字节流(stream)、字符流(reader/writer)来进行文件的同步读写。
nio是以通道(channel)的方式进行一步读取。是JDK4以后提出,从写法或者类库上都比io简洁,但必须依赖于io来创建。
旧io的文件复制:
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path + "z")));
String s;
while ((s = br.readLine())!=null){
pw.write(s+"\n");
}
br.close();
pw.close();
nio的文件复制:
FileChannel in = new FileInputStream("../fc.in").getChannel();
FileChannel out = new FileOutputStream("../fc.out1").getChannel();
//type 1:
// ByteBuffer buffer = ByteBuffer.allocate(GetChannel.BSIZE);
// while (in.read(buffer)!=-1){
// buffer.flip();
// out.write(buffer);
// buffer.clear();
// }
//type 2:
in.transferTo(0,in.size(),out);
//type 3:
out.transferFrom(in,0,in.size());
nio在读入文件时,需要依靠ByteBuffer来存储读到的字节数组,ByteBuffer.flip()可以开启快速存取模式(将当前位置置0),每次读取完下一次读取前需要清除缓存ByteBuffer.clear()。
-- 在ByteBuffer中,asCharBuffer()方法会将字节以字符的形式输出。该方法存在弊端:
public class BufferToText {
public static int BSIZE=1024;
static String path="../data2.out";
public static void main(String[] args) throws IOException {
FileChannel fc = new FileOutputStream(path).getChannel();
fc.write(ByteBuffer.wrap("wa haha haha \n".getBytes()));//write sth
fc.close();
//Read the file
fc = new FileInputStream(path).getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());//此处采用JAVA默认的UTF-16BE来转换,会乱码
buff.rewind();
String encoding = System.getProperty("file.encoding");//the current java file's encoding.
//此处不会乱码,因为采用系统默认的编码编写,此处采用系统默认编码解码
System.out.println("Decoded using"+encoding+":"+ Charset.forName(encoding).decode(buff));
//-------------------------------------------------
fc = new FileOutputStream(path).getChannel();
fc.write(ByteBuffer.wrap(("hanhong hui huahua ").getBytes("UTF-16be")));
fc.close();
//re-read
fc = new FileInputStream(path).getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
//------------------------------------------------
fc = new FileOutputStream(path).getChannel();
buff = ByteBuffer.allocate(100);
buff.asCharBuffer().put("ai xiong xiong ");
fc.write(buff);
fc.close();
//read and display
fc = new FileInputStream(path).getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
}
}