java IO流的学习1

来源:互联网 发布:兄弟连it培训 编辑:程序博客网 时间:2024/06/05 18:50

IO流按流向分为:输出流和输入流。

按操作数据分为:字节流和字符流。

对于IO流的学习本人是从以下几个例子入手的。

例1.复制文本D:test.txt到E盘下

public class CopyText { /**  * @param args  */ public static void main(String[] args) {  BufferedReader bufr = null;  BufferedWriter bufw = null;  try {   bufr = new BufferedReader(new FileReader("D:\\test.txt"));//读取源文件 如果不存在会报错   bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:\\test_copy.txt"),"utf-8"));   //目标文件路径  OutputStreamWriter可设置写入文件的编码如"utf-8"要与源文件一致才可读出正确数据   String len = null;   while((len=bufr.readLine())!=null){//缓存类提供了逐行读取    bufw.write(len);    bufw.newLine();//换行   }  } catch (FileNotFoundException e) {   throw new RuntimeException("文件不存在");  } catch (IOException e) {   throw new RuntimeException("复制文件失败");  }finally{   if(bufr!=null)    try {     bufr.close();    } catch (IOException e) {     throw new RuntimeException("读关闭失败");    }   if(bufw!=null)    try {     bufw.close();    } catch (IOException e) {     throw new RuntimeException("写关闭失败");    }  } }}


例2.复制图片D:\\1.bmp到E盘目录下

 private static void copy1() {  BufferedInputStream ips = null;  BufferedOutputStream ops = null;  try {   ips = new BufferedInputStream(new FileInputStream("D:\\1.bmp"));   ops = new BufferedOutputStream(new FileOutputStream("E:\\1_copy.bmp"));   int i = 0;   while((i=ips.read())!=-1){    ops.write(i);   }  } catch (FileNotFoundException e) {   throw new RuntimeException("文件不存在");  } catch (IOException e) {   throw new RuntimeException("读写文件失败");  }finally{   if(ips!=null)    try {     ips.close();    } catch (IOException e) {     throw new RuntimeException("读关闭失败");    }   if(ops!=null)    try {     ops.close();    } catch (IOException e) {     throw new RuntimeException("写文件失败");    }  } }