电脑
myeclipse和intellij IDEA
第一种:基本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(); }}
第二种:借助于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(); } }}
第三种:使用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(); } }}
jdk 1.6 ,jdk 1.8 myeclipse 2010 ,IDEA 2018.2.2
上面复制文件的方式,如果文件名字已经存在则覆盖已有文件