• Tags
  •         
  • www.breakyizhan.com
  •    

    我们可以使用Java中的FileInputStream和FileOutputStream类将文件从一个位置复制到另一个位置。
    为此,我们必须导入一些特定类的java.io包。所以比如让我们用声明import java.io. *包含整个包。

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

    FileStreams中使用的方法

    1. int read() ; 读取一个字节的数据。出现在FileInputStream中。此方法的其他版本:int read(byte [] bytearray)和int read(byte [] bytearray,int offset,int length)
    2. void write(int b):写入一个数据字节。出现在FileOutputStream中。此方法的其他版本:void write(byte [] bytearray)和void write(byte [] bytearray,int offset,int length);
    /* 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();
        }
    }
    
     
    转载请保留页面地址:https://www.breakyizhan.com/java/5015.html