一、要完成这个程序需要了解的知识点:
1、编写简单的java程序,比如hello world ---废话了。。。。哈哈
2、了解java的文件操作
3、了解java的buffer操作
4、对文件操作的一些异常处理点:1、源文件不能读取到的情况。 2、目的文件创建失败的情况 3、文件锁问题 4、字符乱码问题。。。可能不全啊
这些是需要用到的包
import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception; io操作时需要做异常处理
个人感觉这个效率高的方式,安装计算机来讲,效率高的操作应该是对内存的操作是比较高的了,直接对io的操作应该是相对低的。。所以这里选的是就是读到内存在统一写io,代码如下:
package com.itheima; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; /** * 5、 编写程序拷贝一个文件, 尽量使用效率高的方式. * * @author 2811671413@qq.com * * 1、源文件不能读取到的情况。 2、目的文件创建失败的情况 3、文件锁问题 4、字符乱码问题 */ public class test5 { public static void main(string[] args) throws ioexception { string src_file = "d:/java/java.doc"; string des_file = "d:/java/java_copy.doc"; copyfile(src_file, des_file); system.out.println("ok!"); } public static void copyfile(string src, string des) throws ioexception { bufferedinputstream inbuff = null; bufferedoutputstream outbuff = null; try { // 新建文件输入流并对它进行缓冲 inbuff = new bufferedinputstream(new fileinputstream(src)); // 新建文件输出流并对它进行缓冲 outbuff = new bufferedoutputstream(new fileoutputstream(des)); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len = inbuff.read(b)) != -1) { outbuff.write(b, 0, len); } // 刷新此缓冲的输出流 outbuff.flush(); } finally { // 关闭流 if (inbuff != null) inbuff.close(); if (outbuff != null) outbuff.close(); } } }
其它网友的补充
try { file inputfile = new file(args[0]); if (!inputfile.exists()) { system.out.println("源文件不存在,程序终止"); system.exit(1); } file outputfile = new file(args[1]); inputstream in = new fileinputstream(inputfile); outputstream out = new fileoutputstream(outputfile); byte date[] = new byte[1024]; int temp = 0; while ((temp = in.read(date)) != -1) { out.write(date); } in.close(); out.close(); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); }