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

java文件复制功能实现

Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。      Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点 。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等  。
工具/原料
1

电脑

2

myeclipse和intellij IDEA

方法/步骤
1

第一种:基本copy通过字节流。1、具体代码如下所示:import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;public class Test8 { public static void main(String[] args) { ByteArrayOutputStream bos = null; BufferedInputStream in = null; try { File file = new File('D:/Documents/Downloads/新建文件夹 (2)/代理合同.pdf'); if (!file.exists()) { throw new FileNotFoundException('file not exists'); } in = new BufferedInputStream(new FileInputStream(file)); bos = new ByteArrayOutputStream((int) file.length()); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } copyFile(bos.toByteArray(), 'd:/test.pdf'); System.out.println(bos.toByteArray()); } catch (Exception e) {} } public static void copyFile(byte[] fileByte, String filePath) throws Exception { File file = new File(filePath); FileOutputStream fs = new FileOutputStream(file); BufferedOutputStream bo = new BufferedOutputStream(fs); bo.write(fileByte); bo.close(); }}

2

第二种:借助于java.nio.channels.FileChannel实现复制文件。代码如下所示:import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.channels.FileChannel;public class Test8 { public static void main(String[] args) throws Exception { File source = new File('d:/test.pdf'); if (source.exists()) { File dest = new File('d:/test2.pdf'); copyFileChannels(source, dest); } else { System.out.println('原文件不存在!'); } } public static void copyFileChannels(File source, File dest) throws IOException { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(dest).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { inputChannel.close(); outputChannel.close(); } }}

3

第三种:使用java7之后提供的java.nio.file.Files实现。代码如下:import java.io.*;import java.nio.file.Files;public class CopyTest { 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.6 ,jdk 1.8 myeclipse 2010 ,IDEA 2018.2.2

2

上面复制文件的方式,如果文件名字已经存在则覆盖已有文件

推荐信息