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

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

时间:2022-09-04 22:25:02浏览次数:82  
标签:文件 java String 复制 oldPath File new 拷贝

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

这篇文章主要介绍了java复制文件的4种方式,通过实例带给大家介绍了java 拷贝文件到另一个目录下的方法,需要的朋友可以参考下

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

1. 使用FileStreams复制

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

  1. private static void copyFileUsingFileStreams(File source, File dest)
  2. throws IOException {
  3. InputStream input = null;
  4. OutputStream output = null;
  5. try {
  6. input = new FileInputStream(source);
  7. output = new FileOutputStream(dest);
  8. byte[] buf = new byte[1024];
  9. int bytesRead;
  10. while ((bytesRead = input.read(buf)) > 0) {
  11. output.write(buf, 0, bytesRead);
  12. }
  13. } finally {
  14. input.close();
  15. output.close();
  16. }
  17. }

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

2. 使用FileChannel复制

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

  1. private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
  2. FileChannel inputChannel = null;
  3. FileChannel outputChannel = null;
  4. try {
  5. inputChannel = new FileInputStream(source).getChannel();
  6. outputChannel = new FileOutputStream(dest).getChannel();
  7. outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
  8. } finally {
  9. inputChannel.close();
  10. outputChannel.close();
  11. }
  12. }

3. 使用Commons IO复制

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

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

4. 使用Java7的Files类复制

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

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

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

  1. package com.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. public class TestHtml {
  7. /**
  8. * 复制单个文件
  9. * @param oldPath String 原文件路径 如:c:/fqf.txt
  10. * @param newPath String 复制后路径 如:f:/fqf.txt
  11. * @return boolean
  12. */
  13. public void copyFile(String oldPath, String newPath) {
  14. try {
  15. int bytesum = 0;
  16. int byteread = 0;
  17. File oldfile = new File(oldPath);
  18. if (oldfile.exists()) { //文件存在时
  19. InputStream inStream = new FileInputStream(oldPath); //读入原文件
  20. FileOutputStream fs = new FileOutputStream(newPath);
  21. byte[] buffer = new byte[1444];
  22. int length;
  23. while ( (byteread = inStream.read(buffer)) != -1) {
  24. bytesum += byteread; //字节数 文件大小
  25. System.out.println(bytesum);
  26. fs.write(buffer, 0, byteread);
  27. }
  28. inStream.close();
  29. }
  30. }
  31. catch (Exception e) {
  32. System.out.println("复制单个文件操作出错");
  33. e.printStackTrace();
  34. }
  35. }
  36. /**
  37. * 复制整个文件夹内容
  38. * @param oldPath String 原文件路径 如:c:/fqf
  39. * @param newPath String 复制后路径 如:f:/fqf/ff
  40. * @return boolean
  41. */
  42. public void copyFolder(String oldPath, String newPath) {
  43. try {
  44. (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
  45. File a=new File(oldPath);
  46. String[] file=a.list();
  47. File temp=null;
  48. for (int i = 0; i < file.length; i++) {
  49. if(oldPath.endsWith(File.separator)){
  50. temp=new File(oldPath+file[i]);
  51. }
  52. else{
  53. temp=new File(oldPath+File.separator+file[i]);
  54. }
  55. if(temp.isFile()){
  56. FileInputStream input = new FileInputStream(temp);
  57. FileOutputStream output = new FileOutputStream(newPath + "/" +
  58. (temp.getName()).toString());
  59. byte[] b = new byte[1024 * 5];
  60. int len;
  61. while ( (len = input.read(b)) != -1) {
  62. output.write(b, 0, len);
  63. }
  64. output.flush();
  65. output.close();
  66. input.close();
  67. }
  68. if(temp.isDirectory()){//如果是子文件夹
  69. copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
  70. }
  71. }
  72. }
  73. catch (Exception e) {
  74. System.out.println("复制整个文件夹内容操作出错");
  75. e.printStackTrace();
  76. }
  77. }
  78. public static void main(String[] args)throws Exception {
  79. // //这是你的源文件,本身是存在的
  80. // File beforefile = new File("C:/Users/Administrator/Desktop/Untitled-2.html");
  81. //
  82. // //这是你要保存之后的文件,是自定义的,本身不存在
  83. // File afterfile = new File("C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html");
  84. //
  85. // //定义文件输入流,用来读取beforefile文件
  86. // FileInputStream fis = new FileInputStream(beforefile);
  87. //
  88. // //定义文件输出流,用来把信息写入afterfile文件中
  89. // FileOutputStream fos = new FileOutputStream(afterfile);
  90. //
  91. // //文件缓存区
  92. // byte[] b = new byte[1024];
  93. // //将文件流信息读取文件缓存区,如果读取结果不为-1就代表文件没有读取完毕,反之已经读取完毕
  94. // while(fis.read(b)!=-1){
  95. // //将缓存区中的内容写到afterfile文件中
  96. // fos.write(b);
  97. // fos.flush();
  98. // }
  99. String oldPath="C:/Users/Administrator/Desktop/Untitled-2.html";
  100. String newPath="C:/Users/Administrator/Desktop/jiekou0/Untitled-2.html";
  101. TestHtml t=new TestHtml();
  102. t.copyFile(oldPath, newPath);
  103. }
  104. }

总结

以上所述是小编给大家介绍的java复制文件的4种方式及拷贝文件到另一个目录下的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

https://blog.csdn.net/dxyzhbb/article/details/110388594

标签:文件,java,String,复制,oldPath,File,new,拷贝
From: https://www.cnblogs.com/sunny3158/p/16656318.html

相关文章

  • 第三方库openPyxl读取excel文件
    importopenpyxlfromopenpyxl.worksheet.worksheetimportWorksheetdefopenpyxl_read():#1、打开文件workbook=openpyxl.load_workbook("cases.xlsx")......
  • python 打包代码成可执行文件
    python项目打包成可执行文件为了方便程序的运行,Python提供了第三方库pyinstaller可以很方便的将项目打包成可执行的exe程序,安装方法:pipinstallpyinstaller1、使用方法:......
  • ansible加密解密文件(vault)
                                 ......
  • Java实现文件下载Zip压缩
    Java实现文件下载Zip压缩目录一、概述二、代码功能实现一、概述开发过程中碰到一个需求,需要将服务器上的多个文件打包为zip,并进行下载响应到客户端,写了一个Demo总......
  • 加载properties文件,创建c3p0数据源
    //加载properties文件ResourceBundlerb=ResourceBundle.getBundle("properties文件名称");Stringdriver=rb.getString("properties文件中数据库驱动对应的key值");St......
  • 如何使用 ABAP 代码解析 XML 文件
    正如本教程的开篇介绍文章SAPOData开发教程-从入门到提高(包含SEGW,RAP和CDP)所提到的,SAPOData服务开发,从实现技术上来说,可以分为三大类。因此本教程也分为三大......
  • 基于开源方案构建统一的文件在线预览与office协同编辑平台的架构与实现历程
    基于开源方案构建统一的文件在线预览与office协同编辑平台的架构与实现历程 大家好,又见面了。在构建业务系统的时候,经常会涉及到对附件的支持,继而又会引申出对附件在......
  • java开学测试
    石家庄铁道大学2022年秋季  2021 级课堂测试试卷(一)(15分)课程名称: JAVA语言程序设计  任课教师: 王建民        考试时间: 150 分钟   一、考试要求:1......
  • *第十三章 文件系统
                                        ......
  • img文件编辑_用 Vim 编辑 Markdown 时直接粘贴图片
    效果演示: 使用方法安装这个插件没有其它依赖,使用自己习惯的插件管理方式安装就好。比如我使用Vundle[2],在vimrc里添加Plugin'ferrine/md-img-paste.vim'然后......