java 字节拷贝_java实现文件拷贝的几种方式(全!!)

一、前言:下面例子中,所有异常处理均采用抛出的形式,各位千万不要效仿

二、几种拷贝文件的方式

2.1 字节流的形式

public static void byteCopy(String sourcePath,String target) throws IOException {

//1.创建输入流

InputStream iStream = new FileInputStream(sourcePath);

//2.创建输出流

OutputStream oStream = new FileOutputStream(target);

//3.一部分一部分读出

byte[] bytes = new byte[10*1024];

int br;//实际的读取长度

while((br =iStream.read(bytes))!=-1) {//判断是否读到末尾

oStream.write(bytes, 0, br);

}

//4.清空缓存

oStream.flush();

//5.关闭流

if(iStream!=null) {

iStream.close();

}

if(oStream!=null) {

oStream.close();

}

}

2.2 字节流一次复制完成,缺点是:只能应用于小文件

public static void byteCopy2(String sourcePath,String target) throws IOException {

//1.创建输入流

InputStream iStream = new FileInputStream(sourcePath);

//2.创建输出流

OutputStream oStream = new FileOutputStream(target);

int len = iStream.available();

//3.全部读出

byte[] bytes = new byte[len];

iStream.read(bytes);

oStream.write(bytes, 0, len);

//4.清空缓存

oStream.flush();

//5.关闭流

if(iStream!=null) {

iStream.close();

}

if(oStream!=null) {

oStream.close();

}

}

2.3 带缓冲的字节流

public static void byteCopy3(String sourcePath,String target) throws IOException {

//1.创建输入流

BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sourcePath));

//2.创建输出流

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(target),1024*1024);

//3.一部分一部分读出

byte[] bytes = new byte[10*1024];

int br;//实际的读取长度

while((br =bufferedInputStream.read(bytes))!=-1) {//判断是否读到末尾

bufferedOutputStream.write(bytes, 0, br);

}

//4.清空缓存

bufferedOutputStream.flush();

//5.关闭流

if(bufferedInputStream!=null) {

bufferedInputStream.close();

}

if(bufferedOutputStream!=null) {

bufferedOutputStream.close();

}

}

2.4 字符流完成,缺点:不能指定字符集,不建议使用

public static void CharCopy(String sourcePath,String target) throws IOException{

Reader reader = new FileReader(sourcePath);

Writer writer = new FileWriter(target);

char[] c = new char[10];

int read;

while((read = reader.read(c))!=-1) {

writer.write(c, 0, read);

}

writer.flush();

if(reader!=null) {

reader.close();

}

if(writer!=null) {

writer.close();

}

}

2.5 标准的字符流实现,能指定字符集,一行一行读出,true表示追加

public static void CharCopy2(String sourcePath,String target) throws IOException{

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath), "utf-8"));

PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(target,true),"utf-8"));

String line;

while((line = bufferedReader.readLine())!=null) {

printWriter.write(line+"\n");

}

if(bufferedReader != null) {

bufferedReader.close();

}

if(printWriter != null) {

printWriter.close();

}

}

2.6 NIO实现文件拷贝(用transferTo的实现 或者transferFrom的实现),这里是transferTo的实现。

public static void NIOCopyFile(String source,String target) throws Exception{

//1.采用RandomAccessFile双向通道完成,rw表示具有读写权限

RandomAccessFile fromFile = new RandomAccessFile(source,"rw");

FileChannel fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile(target,"rw");

FileChannel toChannel = toFile.getChannel();

long count = fromChannel.size();

while (count > 0) {

long transferred = fromChannel.transferTo(fromChannel.position(), count, toChannel);

count -= transferred;

}

if(fromFile!=null) {

fromFile.close();

}

if(fromChannel!=null) {

fromChannel.close();

}

}

2.7 NIO实现文件自身内容拷贝(追加到末尾)

public static void main(String[] args) throws Exception {

//1.获取双向通道

RandomAccessFile file = new RandomAccessFile("C:\\Users\\num11\\Desktop\\grade.txt","rw");

//2.得到通道

FileChannel channel = file.getChannel();

//3.定义缓存

ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

if(channel.read(byteBuffer)!= -1){ //判断是否读到末尾

//4.反转

byteBuffer.flip();

channel.write(byteBuffer);

byteBuffer.clear();

}

if(file != null){

file.close();

}

}

2.8 java.nio.file.Files.copy()实现文件拷贝,其中第三个参数决定是否覆盖

public static void copyFile(String source,String target){

Path sourcePath = Paths.get(source);

Path destinationPath = Paths.get(target);

try {

Files.copy(sourcePath, destinationPath,

StandardCopyOption.REPLACE_EXISTING);

} catch (IOException e) {

e.printStackTrace();

}

}

三、总结

以上方法中经过测试,NIO实现的方式的执行效率最高

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现拷贝几种方式,下面是其中两种常用的方式: 1. 使用Cloneable接口和clone()方法: Java中的Object类提供了一个clone()方法,通过实现Cloneable接口并重写clone()方法,可以实现对象的深拷贝。具体步骤如下: - 在需要进行深拷贝的类中实现Cloneable接口。 - 重写clone()方法,在方法内部使用super.clone()进行浅拷贝,然后对引用类型的属性进行深拷贝。 - 在使用时,通过调用clone()方法创建一个新的对象。 以下是一个示例代码: ```java public class MyClass implements Cloneable { private int number; private MyObject myObject; public MyClass(int number, MyObject myObject) { this.number = number; this.myObject = myObject; } @Override protected Object clone() throws CloneNotSupportedException { MyClass cloned = (MyClass) super.clone(); cloned.myObject = (MyObject) myObject.clone(); return cloned; } } public class MyObject implements Cloneable { // ... @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } ``` 2. 使用序列化和反序列化: 另一种实现拷贝方式是通过将对象进行序列化和反序列化来创建一个新的对象。具体步骤如下: - 在需要进行深拷贝的类中实现Serializable接口。 - 将对象写入到一个字节流中,然后再从字节流中读取出来,即可得到一个新的对象。 以下是一个示例代码: ```java import java.io.*; public class MyClass implements Serializable { private int number; private MyObject myObject; public MyClass(int number, MyObject myObject) { this.number = number; this.myObject = myObject; } public MyClass deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (MyClass) ois.readObject(); } } public class MyObject implements Serializable { // ... } ``` 这两种方式都可以实现拷贝,具体选择哪种方式取决于具体的需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值