字节流:InputStream,OutStream
字符流:Reader,Writer
字符流专门处理用来处理包含文字的文件,可以指定文件的编码方式
字节流可以指定一次传输的大小,常常用来处理图片,视屏等大文件
一般txt的编码方式是ACSII码,比如你写入"12abc",实际存入计算机的是81—82—97—98—99,的二进制
下面以两个例子来阐述字符流和字节流
字符流:
/**
* 字符流方式,拷贝文件
* @author Li Jia Xuan
* @version 1.0
* @since 2012-10-30
* @time 上午10:53:32
*/
public class TestCopy {
/**
*
* @param source
* @param target
*/
public static void copy(String source, String target) {
if (!source.equals("") && !target.equals("")) {
File sourcefile = new File(source);
File targetfile = new File(target);
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(
new FileInputStream(sourcefile)));
// bw=new BufferedWriter(new FileWriter(targetfile));
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(targetfile)));
String line = "";
while ((line = br.readLine()) != null) {
bw.write(line);
}
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeIO(br,bw);
}
}
}
/**
* 关闭流,一般采取先开后关、由外向内的原则
* @param br
* @param bw
*/
public static void closeIO(BufferedReader br,BufferedWriter bw){
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}