JAVA 的IO操作(五)简单文件复制

来源:互联网 发布:主人网络个访问网络 编辑:程序博客网 时间:2024/05/01 09:04

完成文件的复制有一下两种方式操作:

1、将源文件中的内容全部读取到内存总,并一次性写入到目标文件中。

2、不将源文件中的内容全部读取进来,而是采用边读边写的方式。

很明显采用第二种方式更合理,因为将源文件的内容一次性读取进来的话,如果文件内容过多,则整个内存是无法装下的,程序肯定会出异常。而采用边读边写的方式,则肯定要比全部读进来性能更高很多。


以下例子比较简单,没有处理异常和判断。

package org.yts.iowriterreaderdemo;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class CopyDemo {public static void main(String args[]) throws Exception{File file1 = new File("e:" + File.separator + "ttt.txt");File file2 = new File("e:" + File.separator + "aaa.txt");InputStream in = new FileInputStream(file1);OutputStream out = new FileOutputStream(file2);int temp = 0;while((temp=in.read()) != -1){out.write(temp);}System.out.println("复制完成!");in.close();out.close();}}


教材中例子,采用命令行 输入:java Copy 源文件路径  目标文件路径 

主要看其中的判断:

import java.io.* ;public class Copy{public static void main(String args[]){if(args.length!=2){// 判断是否是两个参数System.out.println("输入的参数不正确。") ;System.out.println("例:java Copy 源文件路径 目标文件路径") ;System.exit(1) ;// 系统退出}File f1 = new File(args[0]) ;// 源文件的File对象File f2 = new File(args[1]) ;// 目标文件的File对象if(!f1.exists()){System.out.println("源文件不存在!") ;System.exit(1) ;}InputStream input = null ;// 准备好输入流对象,读取源文件OutputStream out = null ;// 准备好输出流对象,写入目标文件try{input = new FileInputStream(f1) ;}catch(FileNotFoundException e){e.printStackTrace() ;}try{out = new FileOutputStream(f2) ;}catch(FileNotFoundException e){e.printStackTrace() ;}if(input!=null && out!=null){// 判断输入或输出是否准备好int temp = 0 ;try{while((temp=input.read())!=-1){// 开始拷贝out.write(temp) ;// 边读边写}System.out.println("拷贝完成!") ;}catch(IOException e){e.printStackTrace() ;System.out.println("拷贝失败!") ;}try{input.close() ;// 关闭out.close() ;// 关闭}catch(IOException e){e.printStackTrace() ;}}}}



0 0