IO流复制文件及文件夹

Myth丶恋晨 2022-04-11 10:53 375阅读 0赞

1.复制文件:

提示:可使用字节流和字符流实现

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. public class CopyMp4 {
  7. public static void main(String[] args) {
  8. // 在指定路径下创建文件
  9. File file = new File("E:/java/land.mp4");
  10. try {
  11. // 字节输入流:把硬盘中的文件读取到内存,相当于打开文件
  12. FileInputStream in = new FileInputStream(file);
  13. // 建立一个缓存区
  14. byte[] b = new byte[(int) file.length()];
  15. // 读取文件内容到缓冲区
  16. in.read(b);
  17. // 关闭字节流输入
  18. in.close();
  19. // 字节输出流,是从内存写入数据到硬盘文件
  20. FileOutputStream o = new FileOutputStream("E:/aa/a.mp4", true);
  21. // 讲缓存区的b写入指定文件夹
  22. o.write(b);
  23. // 关闭字节流输出
  24. o.close();
  25. } catch (FileNotFoundException e) {
  26. e.printStackTrace();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

2.复制文件夹

提示:可使用字节流和字符流进行实现

  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. public class copyDirDemo {
  8. public static void main(String[] args) {
  9. try {
  10. copyDirDemo.copyDir(new File("E:/aa"), new File("E:/java/bb"));
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. public static void copyDir(File oldFile, File newFile) throws IOException {
  16. // if(!newFile.exists()){
  17. newFile.mkdirs();
  18. // }
  19. File[] files = oldFile.listFiles();
  20. for (File file : files) {
  21. if (file.isDirectory()) {
  22. copyDir(file, new File(newFile.getAbsolutePath() + "//" + file.getName()));
  23. }
  24. if (file.isFile()) {
  25. /**
  26. * 使用字节流复制文件夹
  27. */
  28. /*
  29. * FileInputStream fis=new FileInputStream(file);
  30. * FileOutputStream fos=new
  31. * FileOutputStream(newFile.getAbsolutePath()+"\\"+file.getName(
  32. * )); byte[] b=new byte[1024*1024]; int length=0;
  33. * while((length=fis.read(b))!=-1){ fos.write(b,0,length);}
  34. * fos.close(); fis.close();
  35. */
  36. /**
  37. * 使用字符流复制文件夹
  38. */
  39. BufferedReader in = new BufferedReader(new FileReader(file));
  40. BufferedWriter out = new BufferedWriter(
  41. new FileWriter(newFile.getAbsolutePath() + "\\" + file.getName()));
  42. String line = null;
  43. while ((line = in.readLine()) != null) {
  44. out.write(line);
  45. out.newLine();
  46. }
  47. in.close();
  48. out.close();
  49. }
  50. }
  51. }
  52. }

发表评论

表情:
评论列表 (有 0 条评论,375人围观)

还没有评论,来说两句吧...

相关阅读

    相关 使用IO复制文件

    对文件的读取也是经常会遇到的操作,那么哪种方式效率更快呢,今天来做个测试。 首先能想到的就是,应该采用字节流对文件进行复制,文件可以是任何形式,如图片、视频、办公文档、压缩文