io包是以字節(jié)流(stream)、字符流(reader/writer)來進(jìn)行文件的同步讀寫。
nio是以通道(channel)的方式進(jìn)行一步讀取。是JDK4以后提出遥缕,從寫法或者類庫上都比io簡潔,但必須依賴于io來創(chuàng)建宵呛。
舊io的文件復(fù)制:
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的文件復(fù)制:
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在讀入文件時(shí),需要依靠ByteBuffer來存儲(chǔ)讀到的字節(jié)數(shù)組夕凝,ByteBuffer.flip()可以開啟快速存取模式(將當(dāng)前位置置0)宝穗,每次讀取完下一次讀取前需要清除緩存ByteBuffer.clear()。
-- 在ByteBuffer中码秉,asCharBuffer()方法會(huì)將字節(jié)以字符的形式輸出逮矛。該方法存在弊端:
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默認(rèn)的UTF-16BE來轉(zhuǎn)換,會(huì)亂碼
buff.rewind();
String encoding = System.getProperty("file.encoding");//the current java file's encoding.
//此處不會(huì)亂碼转砖,因?yàn)椴捎孟到y(tǒng)默認(rèn)的編碼編寫须鼎,此處采用系統(tǒng)默認(rèn)編碼解碼
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());
}
}