多语言展示
当前在线:1425今日阅读:26今日分享:39

java实现文件复制功能

Java的核心库java.io提供了全面的IO接口。包括:文件读写、标准设备输出等。Java中IO是以流为基础进行输入输出的,所有数据被串行化写入输出流,或者从输入流读入。
工具/原料
1

电脑

2

intellij IDEA

方法/步骤
1

第一步骤:创建一个java项目。1、file--》new--》project...或者Model...打开创建窗口2、输入项目名称“copyFile”--》finish完成3、项目结果如下所示:

2

第二步骤:使用java的FileStreams复制。特点是对于只向的文件如果不存在则直接创建,如果存在直接覆盖完整代码如下所示:引入架包:import java.io.*;import java.nio.channels.FileChannel;public static void testFileStreams(){    FileInputStream fls = null;//创建文件输入    FileOutputStream fos = null;// 创建文件输出流    try {        fls = new FileInputStream('E:/图片/捉妖记.jpg');        fos = new FileOutputStream('E:/file/捉妖记.jpg');    } catch (FileNotFoundException e) {        e.printStackTrace();    }    // 边输入边输出(准备数组和temp)    byte[] bytes = new byte[1024];    //以1KB的速度    int temp = 0;    try {        //循环输入        while((temp=fls.read(bytes)) != -1){            try {                //写入输出                fos.write(bytes,0,temp);            } catch (IOException e) {                e.printStackTrace();            }        }        //刷新输出流        fos.flush();        // 关闭输入输出流        fls.close();        fos.close();    } catch (IOException e) {        e.printStackTrace();    }}

3

第三步骤:使用Java的FileChannel复制。FileChannel的实例实际上还是FileStreams,不过对其进行了包装性能上更高一下,也更加方便一点。代码如下:引入架包:import java.io.*;import java.nio.channels.FileChannel;public static void testFileChannel(){    File inFile = new File('E:/图片/捉妖记.jpg');    File outFile = new File('E:/file/捉妖记.jpg');    FileChannel inputChannel = null;    FileChannel outputChannel = null;    try {        inputChannel = new FileInputStream(inFile).getChannel();        outputChannel = new FileOutputStream(outFile).getChannel();        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());   } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        try {            inputChannel.close();        } catch (IOException e) {            e.printStackTrace();        }        try {            outputChannel.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

4

第四步骤:使用Apache的文件工具类FileUtils。这个使用更加简单,但是需要添加tomcat的架包依赖commons-io.jar。public static void main(String[] args) { File inFile = new File('E:/图片/捉妖记.jpg'); File outFile = new File('E:/file/捉妖记.jpg'); try { org.apache.commons.io.FileUtils.copyFile(inFile, outFile); } catch (IOException e) { e.printStackTrace(); } }

5

第五步骤:使用jdk提供的Files引入架包:import java.io.*;import java.nio.file.Files;这个需要jdk1.7以上版本才能支持public static void main(String[] args) {    File inFile = new File('E:/图片/捉妖记.jpg');    File outFile = new File('E:/file/捉妖记.jpg');    try {        Files.copy(inFile.toPath(), outFile.toPath());    } catch (IOException e) {        e.printStackTrace();    }}

注意事项
1

jdk 1.8 IDEA2018.2.2

2

tomcat的commons-io.jar版本不是特别限制tomcat6以上都应该有

推荐信息