首页 > 编程语言 >Java复制文件的4种方式及拷贝文件到另一个目录下的实例代码

Java复制文件的4种方式及拷贝文件到另一个目录下的实例代码

时间:2023-11-14 10:07:02浏览次数:29  
标签:文件 Java String 复制 oldPath File new 拷贝

尽管Java提供了一个可以处理文件的IO操作类。 但是没有一个复制文件的方法。 复制文件是一个重要的操作,当你的程序必须处理很多文件相关的时候。 然而有几种方法可以进行Java文件复制操作,下面列举出4中最受欢迎的方式。

1. 使用FileStreams复制

这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码:

private static void copyFileUsingFileStreams(File source, File dest) 
    throws IOException {   
  InputStream input = null;   
  OutputStream output = null;   
  try { 
      input = new FileInputStream(source); 
      output = new FileOutputStream(dest);     
      byte[] buf = new byte[1024];     
      int bytesRead;     
      while ((bytesRead = input.read(buf)) > 0) { 
        output.write(buf, 0, bytesRead); 
      } 
  } finally { 
    input.close(); 
    output.close(); 
  } 
} 

正如你所看到的我们执行几个读和写操作try的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。

2. 使用FileChannel复制

Java NIO包括transferFrom方法,根据文档应该比文件流复制的速度更快。 这是第二种方法的代码:

private static void copyFileUsingFileChannels(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. 使用Commons IO复制

Apache Commons IO提供拷贝文件方法在其FileUtils类,可用于复制一个文件到另一个地方。它非常方便使用Apache Commons FileUtils类时,您已经使用您的项目。基本上,这个类使用Java NIO FileChannel内部。 这是第三种方法的代码:

private static void copyFileUsingApacheCommonsIO(File source, File dest) 
    throws IOException { 
  FileUtils.copyFile(source, dest); 
} 

4. 使用Java7的Files类复制

如果你有一些经验在Java 7中你可能会知道,可以使用复制方法的Files类文件,从一个文件复制到另一个文件。 这是第四个方法的代码:

private static void copyFileUsingJava7Files(File source, File dest) 
    throws IOException {   
    Files.copy(source.toPath(), dest.toPath()); 
}

下面看下java拷贝文件到另一个目录下的实现代码,具体代码如下所示:

package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class TestHtml {
/** 
* 复制单个文件 
* @param oldPath String 原文件路径 如:c:/fqf.txt 
* @param newPath String 复制后路径 如:f:/fqf.txt 
* @return boolean 
*/ 
public void copyFile(String oldPath, String newPath) { 
try { 
int bytesum = 0; 
int byteread = 0; 
File oldfile = new File(oldPath); 
if (oldfile.exists()) { //文件存在时 
InputStream inStream = new FileInputStream(oldPath); //读入原文件 
FileOutputStream fs = new FileOutputStream(newPath); 
byte[] buffer = new byte[1444]; 
int length; 
while ( (byteread = inStream.read(buffer)) != -1) { 
bytesum += byteread; //字节数 文件大小 
System.out.println(bytesum); 
fs.write(buffer, 0, byteread); 
} 
inStream.close(); 
} 
} 
catch (Exception e) { 
System.out.println("复制单个文件操作出错"); 
e.printStackTrace();
}
}
/** 
* 复制整个文件夹内容 
* @param oldPath String 原文件路径 如:c:/fqf 
* @param newPath String 复制后路径 如:f:/fqf/ff 
* @return boolean 
*/ 
public void copyFolder(String oldPath, String newPath) {
try { 
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 
File a=new File(oldPath); 
String[] file=a.list(); 
File temp=null; 
for (int i = 0; i < file.length; i++) { 
if(oldPath.endsWith(File.separator)){ 
temp=new File(oldPath+file[i]); 
} 
else{ 
temp=new File(oldPath+File.separator+file[i]); 
}
if(temp.isFile()){ 
FileInputStream input = new FileInputStream(temp); 
FileOutputStream output = new FileOutputStream(newPath + "/" + 
(temp.getName()).toString()); 
byte[] b = new byte[1024 * 5]; 
int len; 
while ( (len = input.read(b)) != -1) { 
output.write(b, 0, len); 
} 
output.flush(); 
output.close(); 
input.close(); 
} 
if(temp.isDirectory()){//如果是子文件夹 
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
} 
} 
} 
catch (Exception e) { 
System.out.println("复制整个文件夹内容操作出错"); 
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
// //这是你的源文件,本身是存在的
// File beforefile = new File("C:/Users/Administrator/Desktop/Untitled-2.html");
//
// //这是你要保存之后的文件,是自定义的,本身不存在
// File afterfile = new File("C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html");
//
// //定义文件输入流,用来读取beforefile文件
// FileInputStream fis = new FileInputStream(beforefile);
//
// //定义文件输出流,用来把信息写入afterfile文件中
// FileOutputStream fos = new FileOutputStream(afterfile);
//
// //文件缓存区
// byte[] b = new byte[1024];
// //将文件流信息读取文件缓存区,如果读取结果不为-1就代表文件没有读取完毕,反之已经读取完毕
// while(fis.read(b)!=-1){
// //将缓存区中的内容写到afterfile文件中
// fos.write(b);
// fos.flush();
// }
String oldPath="C:/Users/Administrator/Desktop/Untitled-2.html";
String newPath="C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html";
TestHtml t=new TestHtml();
t.copyFile(oldPath, newPath);
}
}











标签:文件,Java,String,复制,oldPath,File,new,拷贝
From: https://blog.51cto.com/u_16071479/8361107

相关文章

  • Java表达式引擎选型调研分析
    1简介我们项目组主要负责面向企业客户的业务系统,企业的需求往往是多样化且复杂的,对接不同企业时会有不同的定制化的业务模型和流程。我们在业务系统中使用表达式引擎,集中配置管理业务规则,并实现实时决策和计算,可以提高系统的灵活性和响应能力,从而更好地满足业务的需求。举个简......
  • 来来来,一文让你读懂Cocos Creator如何读写JSON文件
    前言在游戏开发过程中,读取配置文件是必不可少的,而使用JSON做配置文件又比较常见,本文重点给大家讲述如何在CocosCreator开发中读取和解析JSON数据文件以及如何写JSON文件。一、JSON简介1.什么是JSONJSON的英文全称是JavaScriptObjectNotation,即JavaScript对象表示法。2.J......
  • 2.4 Windows驱动开发:内核字符串拷贝与比较
    在上一篇文章《内核字符串转换方法》中简单介绍了内核是如何使用字符串以及字符串之间的转换方法,本章将继续探索字符串的拷贝与比较,与应用层不同内核字符串拷贝与比较也需要使用内核专用的API函数,字符串的拷贝往往伴随有内核内存分配,我们将首先简单介绍内核如何分配堆空间,然后再以......
  • Java中ThreadLocal说明 使用线程内变量,完成后需调用remove()方法将其移除,即使异常也
    Java中ThreadLocal说明,完成后需调用remove()方法将其移除,即使异常也记得remove()回收,创建ThreadLocal线程变量publicstaticThreadLocalthreadLocal=newThreadLocal<>();1、ThreadLocal是什么ThreadLocal,即线程变量,是一个以ThreadLocal对象为键、任意对象为值的存储......
  • finalshell报错java.net.UnknownHostException: node2
    前几天是node3连不上,今天早上写作业发现node2又连不上了]$systemctlstatusnetwork.service●network.service-LSB:Bringup/downnetworkingLoaded:loaded(/etc/rc.d/init.d/network;bad;vendorpreset:disabled)Active:active(exited)since二2023-11-1408:......
  • APK没有SO文件就运行不了吗,它有什么作用
    APK(Android应用程序包)中的SO文件,即“.so”文件,是一种特殊的文件格式,用于存储Android应用中的本地库(nativelibraries)。这些本地库通常是用C或C++编写的,然后编译成平台特定的代码。但并不是所有APK都必须含有SO文件才能运行。它们的使用取决于应用的特定需求。可以用生活中的例子......
  • Java开发者的Python快速进修指南:函数基础
    话不多说,今天我们要介绍的是函数。本系列文章追求短而精,今天我们将重点讨论函数以及与Java方法的区别。与Java方法不同,函数不需要像Java方法一样讲究修饰符等其他特性,它只需要使用"def"关键字进行声明。另外,函数的参数也与Java方法有所不同,Java方法中不存在默认参数的概念,而在Pyth......
  • apk里面的so文件包括什么,作用是什么,比喻一下
    在Android的APK文件中,.so 文件是指共享对象(SharedObject)文件,它们有以下特点和作用:本质和组成:.so 文件是Linux系统中的动态链接库(类似于Windows中的.dll 文件)。它们通常是用C或C++编写的,并被编译成机器码。作用:性能优化:由于.so 文件包含编译后的代码,它们可以提高应用的......
  • java如何配置环境变量?详细一点每一个步骤
    配置Java环境变量的步骤在不同操作系统中有所不同。以下是在Windows和Linux系统中配置Java环境变量的详细步骤:在Windows系统中配置Java环境变量下载并安装JavaJDK访问Oracle官网下载JavaDevelopmentKit JDK���。安装JDK,记住安装路径。设置JAVA_HOME环境变量打开“......
  • apk里面的so文件是干啥用的,如何反编译?
    在APK文件中,.so文件是Android应用中使用的本地库文件。这些文件是用C或C++编写的,并被编译成平台特定的机器代码。.so文件的作用通常是为了提高性能(因为C/C++比Java快),处理特定的图形处理、音频处理或任何需要高性能计算的任务。它们也可能用于集成某些第三方库或者防......