设为首页 加入收藏

TOP

Java IO 文件拷贝功能的实现(一)
2018-03-28 09:05:59 】 浏览:829
Tags:Java 文件 拷贝 功能 实现

如果要想实现文件的拷贝操作,有以下两种方法:


方法1、将所有文件的内容一次性读取到程序之中,然后一次性输出;这样的话就需要开启一个跟文件一样大小的数据用于临时保存这些数据,但是当文件过大的时候呢?程序是不是会崩掉呢?欢迎大家踊跃尝试^@^。


方法2、采用边读边写的操作,这样一来效率也提高了,也不会占用过多的内存空间。


所以,我们采用第二种方法,边读边写。


package signal.IO;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class CopyFile {


    /**
    * 定义一个方法来实现拷贝文件的功能
    *
    * @param src 源文件路径
    * @param target 目标文件路径
    * @throws IOException
    */


    public static void CopyFile(File src, File target) throws IOException{
        /**
        * 验证源文件是否存在
        */
        if(!src.exists()){
            System.err.println("There is no such a file !!!");
            System.exit(1);
        }
        /**
        * 验证目标路径是否存在,不存在的话创建父路径
        */
        if(!target.getParentFile().exists()){
            target.getParentFile().mkdirs();
        }


        int temp = 0;  //用作标示是否读取到源文件最后
        InputStream input = new FileInputStream(src);
        OutputStream output = new FileOutputStream(target);


        while((temp = input.read()) != -1){
            output.write(temp);
        }


        input.close();
        output.close();
    }


    public static void main(String[] args) {


        String in = "C:\\Users\\Administrator\\Desktop\\tmp.txt";//源文件路径
        String out = "C:\\Users\\Administrator\\Desktop\\tmp_copy.txt";//目标路径(此时还可以重命名)


        File src = new File(in);
        File target = new File(out);


        try {
            CopyFile(src, target);
            System.out.println("Copy Successfully !");
        } catch (IOException e) {
            System.err.println("ERROR: Something wrong while copying !");
            e.printStackTrace();
        }
    }
}


正如代码中写的那样,我们是一边读取一边写入。使用到的 read() 方法源码如下:


    ...


    /**
    * Reads the next byte of data from the input stream. The value byte is
    * returned as an <code>int</code> in the range <code>0</code> to
    * <code>255</code>. If no byte is available because the end of the stream
    * has been reached, the value <code>-1</code> is returned. This method
    * blocks until input data is available, the end of the stream is detected,
    * or an exception is thrown.
    *
    * <p> A subclass must provide an implementation of this method.
    *
    * @return    the next byte of data, or <code>-1</

首页 上一页 1 2 3 4 5 下一页 尾页 1/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android 自定义ToolBar详细使用 下一篇Java中的Number和Math类简单介绍

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目