21xrx.com
2024-09-17 03:37:42 Tuesday
登录
文章检索 我的文章 写文章
Java实现文件复制操作
2023-06-12 00:08:16 深夜i     --     --
Java 文件复制 InputStream OutputStream

在java中,文件复制是一种基本的操作。使用java实现文件复制有多种方法,其中最常用的是使用InputStream与OutputStream来读写文件。

以下是一个使用InputStream与OutputStream来读写文件的代码示例:


import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileCopy {

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

    String sourceFile = "C:\\Users\\user\\Desktop\\sourceFile.txt";

    String destinationFile = "C:\\Users\\user\\Desktop\\destinationFile.txt";

    FileInputStream fis = null;

    FileOutputStream fos = null;

    try {

      fis = new FileInputStream(sourceFile);

      fos = new FileOutputStream(destinationFile);

      byte[] buffer = new byte[1024];

      int length;

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

        fos.write(buffer, 0, length);

      }

      System.out.println("File Copied successfully!");

    } catch (IOException e) {

      e.printStackTrace();

    } finally {

      fis.close();

      fos.close();

    }

  }

}

以上代码将从源文件路径读取文件内容,然后将其复制到目标文件路径中。在此过程中,使用了InputStream与OutputStream来读写文件。

  
  

评论区

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