java文件复制功能实现

      Java是一门面标的目的对象编程说话,不仅接收了C++说话的各类长处,还摒弃了C++里难以理解的多担当、指针等概念,是以Java说话具有功能壮大和简单易用两个特征 。 Java说话作为静态面标的目的对象编程说话的代表,极好地实现了面标的目的对象理论,许可程序员以优雅的思维体例进行复杂的编程 。
      Java具有简单性、面标的目的对象、分布式、健壮性、平安性、平台自力与可移植性、多线程、动态性等特点 。 Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等   。

需要这些哦
电脑
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();
}
}

java文件复制功能实现

文章插图

java文件复制功能实现

文章插图

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();
}
}
}

java文件复制功能实现

文章插图

java文件复制功能实现

文章插图

java文件复制功能实现

推荐阅读