黑马程序员-IO流(一)

---------------------  android培训、 java培训、期待与您交流! ---------------------
IO流(一)


IO流分为字节流和字符流(字符流的实现也是基于字节流的)。
1.字符流有Reader和Writer两个顶层的抽象类,用于对字符的读入和写出,最常用的实现类有FileReader,FileWriter,BufferedReader和BufferedWriter。BufferedReader和BufferedWriter是装饰类,可装饰字符流,是其有更强的功能(提供readLine和newLine方法)和更优的IO效率(缓冲机制)。


2.字节流有InputStream和OutputStream两个顶层抽象类,用于对字节的输入输出。最常用的实现类有FileInputStream,FileOutputStream,BufferedInputStream和BufferedOutputStream。后两个是装饰类,可装饰字节流,具有更优秀的IO缓冲效率。


3.字符流与字节流的转换通道:InputStreamReader和OutputStreamWriter。其中InputStreamReader修饰InputStream,使字节输入流转换为字符输入流,便于直接使用字符流进行操作。OutputStreamWriter用于修饰OutputStream,使字符输出流转化为字节出流,便于直接使用字符流进行操作。这些转换都是基于数据为字符的前提,不能用于其他数据的操作。而操作字符型的数据最好使用字符流进行,最方便的地方就是可以使用readLine和newLine方法。


4.文件的复制。任意文件的复制不能使用字符流,而应该使用字节流。每读满一个字节数组就写出去,这样就可以了。

public class FileCopyDemo {


public static void main(String[] args) {


int result = copyFile("C:\\","Reader的层次.png","C:\\abcd\\");
if(result == 1)
{
System.out.println("成功");
}

//返回-1失败
//返回 1成功
private static int copyFile(String fromPath, String fileName, String toPath)
{
//FileInputStream fis = null;
//FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;//使用带缓冲的字节流


try
{
bis = new BufferedInputStream(new FileInputStream(fromPath + fileName)) ;
new File(toPath).mkdir();//创建目录
bos = new BufferedOutputStream(new FileOutputStream(toPath + fileName));
byte[] data = new byte[1024];
int len;
while((len = bis.read(data)) != -1)
{
bos.write(data, 0, len);

}
catch(IOException e)//处理异常
{
System.out.println("文件复制出错");
return -1;
}
finally
{
if(bis != null)
{
try{
bis.close();
}
catch(IOException e)
{
System.out.println(e.toString());
return -1;

}
if(bos != null)
{
try{
bos.close();
}
catch(IOException e)
{
System.out.println(e.toString());
return -1;

}


}
return 1;


}
}


5.装饰设计模式:将一个已有的对象进行功能增强,可以定义一个类,将原对象传入,基于原对象已有的功能进行增强。这个类就是装饰类。这样做的好处是使操作更加灵活,关系不臃肿。


6.FileOutputStream由于是节点流,直接对内存进行操作,所以write方法可以直接写入,而不需要额外的flush。其他如字符流都是有缓冲的。


7.使用IO资源时,需要处理异常,不再使用的流需要关闭以释放资源,也防止数据为完全写入(处于缓冲区中)。







---------------------- android培训、 java培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net/heima

你可能感兴趣的:(黑马程序员-IO流(一))