Skip to content

Latest commit

 

History

History
88 lines (63 loc) · 3.05 KB

88.md

File metadata and controls

88 lines (63 loc) · 3.05 KB

如何使用 Java 将文件复制到另一个文件

原文: https://beginnersbook.com/2014/05/how-to-copy-a-file-to-another-file-in-java/

在本教程中,我们将了解如何将一个文件的内容复制到 java 中的另一个文件中。为了复制文件,首先我们可以使用FileInputStream读取文件然后我们可以使用FileOutputStream将读取的内容写入输出文件

下面的代码会将MyInputFile.txt的内容复制到MyOutputFile.txt文件中。如果MyOutputFile.txt不存在,则程序将首先创建文件,然后复制内容。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyExample 
{
    public static void main(String[] args)
    {	
    	FileInputStream instream = null;
	FileOutputStream outstream = null;

    	try{
    	    File infile =new File("C:\\MyInputFile.txt");
    	    File outfile =new File("C:\\MyOutputFile.txt");

    	    instream = new FileInputStream(infile);
    	    outstream = new FileOutputStream(outfile);

    	    byte[] buffer = new byte[1024];

    	    int length;
    	    /*copying the contents from input stream to
    	     * output stream using read and write methods
    	     */
    	    while ((length = instream.read(buffer)) > 0){
    	    	outstream.write(buffer, 0, length);
    	    }

    	    //Closing the input/output file streams
    	    instream.close();
    	    outstream.close();

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

    	}catch(IOException ioe){
    		ioe.printStackTrace();
    	 }
    }
}

输出:

File copied successfully!!

上述程序中使用的方法是:

read()方法

public int read(byte[] b) throws IOException

将此输入流中的b.length个字节数据读入一个字节数组。此方法将阻止,直到某些输入可用。它返回读入缓冲区的总字节数,如果没有更多数据,则返回 -1,因为已到达文件末尾。为了使这个方法在我们的程序中工作,我们创建了一个字节数组buffer并将输入文件的内容读取到相同的内容。由于此方法抛出IOException,因此我们将“读取文件”代码放在try-catch块中以处理异常。

write()方法

public void write(byte[] b,
                  int off,
                  int length)
           throws IOException

将从偏移off开始的指定字节数组的长度字节写入此文件输出流。

调整:

如果输入和输出文件不在同一个驱动器中,则可以在创建文件对象时指定驱动器。例如,如果您的输入文件在C盘中并且输出文件在D盘中,那么您可以创建如下文件对象:

File infile =new File("C:\\MyInputFile.txt");
File outfile =new File("D:\\MyOutputFile.txt");