21xrx.com
2024-09-20 00:47:08 Friday
登录
文章检索 我的文章 写文章
Java实现文件复制的简单代码
2023-06-17 05:16:56 深夜i     --     --
Java 文件复制 代码

在Java中,实现文件复制是非常常见的操作。下面给大家介绍一段简单的Java文件复制代码。

代码如下:


import java.io.*;

public class FileCopy {

  public static void main(String[] args) {

    String sourcePath = "原文件路径";

    String targetPath = "目标文件路径";

    File source = new File(sourcePath);

    File target = new File(targetPath);

    try {

      FileInputStream fis = new FileInputStream(source);

      FileOutputStream fos = new FileOutputStream(target);

      byte[] buffer = new byte[1024];

      int length;

      while ((length = fis.read(buffer)) > 0) {

        fos.write(buffer, 0, length);

      }

      fis.close();

      fos.close();

      System.out.println("文件复制成功!");

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

这段代码非常简单,首先我们需要定义源文件路径和目标文件路径。接着,通过File类对源文件和目标文件进行封装。然后,我们使用try-catch语句打开文件流,读取源文件中的字节数据,并将这些字节数据写入目标文件中,直到源文件读取完毕。最后,关闭文件流并打印出操作成功提示。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复