`
林奇峰
  • 浏览: 40953 次
  • 性别: Icon_minigender_1
  • 来自: 濮阳
社区版块
存档分类
最新评论

文件读取写入标准写法

    博客分类:
  • j2se
阅读更多

 文件读取写入标准写法

public void copy(String src , String des){
  
  InputStream in = null;
  OutputStream out = null;
  
  try {
   in = new FileInputStream(src);//多态应用,FileInputStream继承InputStream
   out = new FileOutputStream(des);//多态应用,FileOutputStream继承OutputStream

   byte[] buf = new byte[1024];//申请1M内存,用于存放读入的数据,其实是作为缓冲(cache)

   int n ;
   while((n = in.read(buf))> 0){// read(buf))指将数据先读入buf内,当buf满时,跳出read方法,并返回buf的容量,然后赋值给n;当buf不满但已经读取完毕就返回buf的实际存放字节数
    out.write(buf, 0, n);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    in.close();//close()方法本身就有可能抛出异常,故而用try catch 包裹;如果抛出异常in就不能正常关闭但是资源还被占用,故而在finally里 in=null;
	       //无论抛出异常与否都将in赋值null,这样有利于垃圾回收机制将其回收;我其实挺建议这样写,涉及到不用资源时,先释放资源再赋值null这样使得垃圾回收更快
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }finally{
    in = null;
    out = null;
   }
  }
 }

 源码解析:

public abstract class InputStream implements Closeable {
    private static final int MAX_SKIP_BUFFER_SIZE = 2048;

    public abstract int read() throws IOException;

    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
        int c = read();//读取一个字节,这也是为什么inputStream是字节流的原因
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;
        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;// read(buf))指将数据先读入buf内,当buf满时,跳出read方法,并返回buf的容量,然后赋值给n;当buf不满但已经读取完毕就返回buf的实际存放字节数
    }
}

 

 

public class FileInputStream extends InputStream//继承自InputStream
{
    public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }
    public native int read() throws IOException;//调用本地方法和系统资源,读取一个字节,这也是为什么inputStream和其子类 是字节流的原因

    private native int readBytes(byte b[], int off, int len) throws IOException;//功能和inputStream的read(byte b[], int off, int len)方法一样,区别就是它是本地方法

    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }
}

 

 

 

分享到:
评论
1 楼 s332401890 2014-11-19  
谢谢博主分享!!!

相关推荐

Global site tag (gtag.js) - Google Analytics