A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 熊永标 中级黑马   /  2013-1-14 12:26  /  1061 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

IO流是InputStream和Outputstream的缩写,即输入输出流。
java流分为字节流和字符流。
字节流。即用于操作字节数据流,用于处理此流的对象有:inputStream体系和OutputStream体系,其下常用的类有:
        1)、文件处理类:FileInputStream,FileOutputStream
        2)、字节缓冲区类:ByteArrayInputStream,ByteArrayOutputStream。
字符流。即读取字节数据时不操作,而是将其缓存起来,在查编码表得到字符后再进行基于字符的处理叫字符流。字符流有Reader体系和Writer体系,其下最常用的类有:
       1)文件处理类:FileReader,FileWriter.
       2)  字符缓冲区类:BufferedReadr,BufferedWriter
转换流。字节流转换为字符流或相反就是统称:转换流。转换流是属于字符流的体系,通过转换流,就可以将有效的数据中进行数据流的转换。还可以将数据编解码。转换流是字
              节流和字符流的桥梁。常用的类有:
       1)InputstreamReader,OutputStreamWriter。他们的构造函数中接受字节流对象。

1 个回复

倒序浏览

既然LZ梳理IO流对象,这里我也学习学习,补通java文件流读写文件需要注意的几点....
1.Reader/Writer 读写二进制文件有问题 下面我写个代码示例下
  1. <div class="blockcode"><blockquote>public void copy{
  2. File src = new File("d:"+File.separator+"a.txt");
  3. File dst = new File("d:"+File.separator+"b.txt");
  4. BufferedReader in = null;
  5. BufferedWriter out = null;
  6. try {
  7.     in = new BufferedReader(new FileReader(src));
  8.     out = new BufferedWriter(new FileWriter(dst));
  9. String line = null;
  10. while((line = in.readLine()) != null) {  // 一行一行的读取文件a.txt
  11. out.write(line+"/r/n");    //把读取的数据写入到b.txt
  12.       }                                                // 问题就这这里,需要注意,若文件a.txt 是ASCII编码格式,则内容能够正确读取,若文件是二进制,读写后的文件与读写前的文件
  13. }catch (Exception e) {               // 有很大的区别,我把 readLine() 改写 read(char[]) 仍然不能正确读写二进制文件,下面又是需要注意的几点,看代码实例
  14. e.printStackTrace();
  15. }finally {
  16. if(in != null) {
  17.   try {
  18.      in.close();   //关闭流
  19. }catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. if(out != null) {
  24. try {
  25. out.close();  //关闭流
  26. }catch (Exception e) {
  27.   e.printStackTrace();
  28. }
  29. }
  30. }
复制代码
2. read[byte[] b,int offset,int length] ,注意offset 不是指全文件的全文,是字节数组b的偏移量,相当于c语言的文件指针
现在晓得Reader/Writer不能读取二进制文件,Reader/Writer是字符流,只能用BufferInputStream/BufferOutputStream
上面的代码改了 一下,请看....
  1. public void copy{
  2. File src = new File("d:"+File.separator+"a.txt");
  3. File dst = new File("d:"+File.separator+"b.txt");
  4. BufferedInputStream in = null;
  5. BufferedOutStream out = null;
  6. try {
  7. in = new BufferedInputStream(new FileReader(src));
  8. out = new BufferedOutputStream(new FileWriter(dst));
  9. byte[] b=new byte[1024];
  10. int offset=0;
  11. int length=-1;
  12. while((length=in.read(b,offset,1024))!=-1) {  // 一行一行的读取文件a.txt,每次读取1024字节,然后写入1024字节
复制代码
3. 在用length=(read,b,0,1024) 读取数据时候,应该使用write(b,0,length)来写最好 上面修改部分代码
int len=-1;
byte[] b=new byte[10];
while((len=in.read(b))!=-1){
out.wirte(b,0,len);
}

4. flush() 和 close
   写入缓冲区后,很多内容停留在内存里,而不是在文件里,数据有可能丢失,再用close()中调用flush(),文件一旦写完后关闭文件流close().


回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马