在Java中使用FileStreams复制文件

2021年3月16日16:32:13 发表评论 608 次浏览

我们可以使用Java中的FileInputStreamFileOutputStream类将文件从一个位置复制到另一位置。

为此, 我们必须导入一些特定的java.io包类。例如, 让我们用语句import java.io. *包含整个包;

复制文件的主要逻辑是读取与FileInputStream变量关联的文件, 并将读取的内容写入与FileOutputStream变量关联的文件。

程序中使用的方法

  1. int read();读取一个字节的数据。存在于FileInputStream中。此方法的其他版本:int read(byte [] bytearray)和int read(byte [] bytearray, int偏移量, int长度)
  2. void write(int b):写入一个字节的数据。存在于FileOutputStream中。此方法的其他版本:void write(byte [] bytearray)和void write(byte [] bytearray, int偏移量, int长度);
/* Program to copy a src file to destination.
    The name of src file and dest file must be
    provided using command line arguments where
    args[0] is the name of source file and
    args[1] is name of destination file */
  
import java.io.*;
class src2dest
{
     public static void main(String args[])
     throws FileNotFoundException, IOException
     {
         /* If file doesnot exist FileInputStream throws
            FileNotFoundException and read() write() throws
            IOException if I/O error occurs */
         FileInputStream fis = new FileInputStream(args[ 0 ]);
  
         /* assuming that the file exists and need not to be
            checked */
         FileOutputStream fos = new FileOutputStream(args[ 1 ]);
  
         int b;
         while  ((b=fis.read()) != - 1 )
             fos.write(b);
  
         /* read() will readonly next int so we used while
            loop here in order to read upto end of file and
            keep writing the read int into dest file */
         fis.close();
         fos.close();
     }
}

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: