一、要完成這個(gè)程序需要了解的知識點(diǎn):
1、編寫簡單的Java程序,比如hello world ---廢話了。。。。哈哈
2、了解java的文件操作
3、了解java的buffer操作
4、對文件操作的一些異常處理點(diǎn):1、源文件不能讀取到的情況。 2、目的文件創(chuàng)建失敗的情況 3、文件鎖問題 4、字符亂碼問題。。。可能不全啊
這些是需要用到的包
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; IO操作時(shí)需要做異常處理
個(gè)人感覺這個(gè)效率高的方式,安裝計(jì)算機(jī)來講,效率高的操作應(yīng)該是對內(nèi)存的操作是比較高的了,直接對IO的操作應(yīng)該是相對低的。。所以這里選的是就是讀到內(nèi)存在統(tǒng)一寫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、 編寫程序拷貝一個(gè)文件, 盡量使用效率高的方式.
- *
- * @author [email protected]
- *
- * 1、源文件不能讀取到的情況。 2、目的文件創(chuàng)建失敗的情況 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 {
- // 新建文件輸入流并對它進(jìn)行緩沖
- inBuff = new BufferedInputStream(new FileInputStream(src));
- // 新建文件輸出流并對它進(jìn)行緩沖
- outBuff = new BufferedOutputStream(new FileOutputStream(des));
- // 緩沖數(shù)組
- byte[] b = new byte[1024 * 5];
- int len;
- while ((len = inBuff.read(b)) != -1) {
- outBuff.write(b, 0, len);
- }
- // 刷新此緩沖的輸出流
- outBuff.flush();
- } finally {
- // 關(guān)閉流
- if (inBuff != null)
- inBuff.close();
- if (outBuff != null)
- outBuff.close();
- }
- }
- }
其它網(wǎng)友的補(bǔ)充
- 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();
- }