java文件复制代码片断(java实现文件拷贝)
发布时间:2020-05-23 21:04:13 所属栏目:Java 来源:互联网
导读:一、要完成这个程序需要了解的知识点:1、编写简单的Java程序,比如helloworld---废话了。。。。哈哈
|
一、要完成这个程序需要了解的知识点: 1、编写简单的Java程序,比如hello world ---废话了。。。。哈哈 这些是需要用到的包 import java.io.BufferedInputStream; 个人感觉这个效率高的方式,安装计算机来讲,效率高的操作应该是对内存的操作是比较高的了,直接对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,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();
}
您可能感兴趣的文章:
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
