IO流-字节流,字符流
一,第一个轮子--关流
将关流写成一个方法,以后无论有多少个需要关的流,只需调用方法传入要关闭的流即可
public static void closeAll(Closeable ...closeables){
if(closeables == null){
return;
}
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二,BufferedInputStream和BufferedOutputStream字节流
File srcFile = new File(srcPath);
File desFile = new File(desPath);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile);
int pos = 0; //pos=>position
byte[] buff = new byte[1024];
while((pos = bis.read(buff)) != -1){
bos.write(buff,0,pos);
}
bos.flush();//BufferedOutputStream后面要加flush,无论bos里面的数据满没满都将里面的数据写进硬盘中.
IOUtils.closeAll(bis,bos);//引用方法关流
三,BufferedReader和PrintWriter字符流
1,BufferedReader:输入流
File file = new File("text.txt");
BufferedReader reader = new BufferedRreader(new InputStreamReader(FileInputStream(file)));//创建字符流的对象
String line = "";
StringBuilder sb = new StringBuilder();//创建拼接字符串的对象
while((line = reader.readLine()) != null){
sb.append(line).append("\n");//手动拼接换行
}
String result = sb.toString();//转换成字符串
IOUtils.colseAll(reader);//调用方法关流
2.PrintWriter:输出流
File file = new File("text.txt");
PrintWriter pw = new PrintWriter(new OutputSreamWriter(new FileOutputStream(file)));//创建字符输入流对象
pw.println(1);//写入数字,换行
pw.print("你好");//写入字符串,不换行
pw.flush();//同上
IOUtils.closeAll(pw);//关流