IO---Java 文件复制

来源:互联网 发布:房琪 巴基斯坦 知乎 编辑:程序博客网 时间:2024/04/30 22:18
利用FileInputStream及FileOutputStream实现文件的复制操作。

 

FileOutStream out=new FileOutStream(outfile);

如果存在outfile则重构,如果不存在outfile则创建。

FileOutStream out=new FileOutStream(outfile,ture);  append ture or flase

如果存在outfile则追加,如果不存在outfile则创建。

 

实现复制方法:

    public static void sds(File infile, File outfile) throws IOException {        FileInputStream in = new FileInputStream(infile);        FileOutputStream out = new FileOutputStream(outfile);        if (!infile.exists())            throw new IllegalArgumentException("文件" + infile + "不存在");        if (!infile.isFile())            throw new IllegalArgumentException(infile + "不是文件");        byte[] buf = new byte[20 * 1024];        int bytes = 0;        while ((bytes = in.read(buf, 0, buf.length)) != -1) {            out.write(buf, 0, bytes);            out.flush();        }        in.close();        out.close();    }

其中 out.flush:

即清空缓冲区数据,就是说你用读写流的时候,其实数据是先被读到了内存中,然后用数据写到文件中,当你数据读完的时候不代表你的数据已经写完了,因为还有一部分有可能会留在内存这个缓冲区中。这时候如果你调用了 close()方法关闭了读写流,那么这部分数据就会丢失,所以应该在关闭读写流之前先flush(),先清空数据。
拓展:
DataOutputStream out=new DataOutputStream(new FileOutputStream(outfile));
利用DataOutputStream包装可以实现一些类似于writeInt(10)、writeUTF(“中国”) #utf-8、writeChars(“知乎”) utf-16be、
BufferedOutputStream 包装 FileInputStream及FileOutputStream可以用于提高IO性能。
0 0
原创粉丝点击