【问题标题】:How is the write(byte[],int,int) method working?write(byte[],int,int) 方法是如何工作的?
【发布时间】:2017-05-01 18:56:06
【问题描述】:
public class JavaCopyFileProgram {



        public static void main(String[] args)
        {    
            File sourceFile = new File("F:/Study/Java/Java Programs/Factory Methods.txt");

            File destFile = new File("D:/DestFile.txt");

            FileInputStream inStream = null;

            FileOutputStream outStream = null;

            try
            {
                inStream = new FileInputStream(sourceFile);

                outStream = new FileOutputStream(destFile);

                byte[] buffer = new byte[1024];

                int length;

                while ((length = inStream.read(buffer)) != -1) 
                { 
                    outStream.write(buffer, 0, length);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    inStream.close();

                    outStream.close();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }

            System.out.println("Success");
        }
    }   

我无法理解 thw write() 方法是如何工作的?当它第一次被调用时,它将从 0 索引写入字节数组的长度,但是当它被第二次调用时,它如何将新文本附加到前一个文本的末尾?它应该覆盖以前的内容,因为再次以 0 作为起始索引调用 write。如果我理解错了,请帮助我?

【问题讨论】:

    标签: java fileinputstream fileoutputstream


    【解决方案1】:

    write 方法中的起始偏移量不是指FileOutputStream 中的偏移量,而是指您写入的数组中的偏移量。

    您可以阅读in the documentation of OutputStream(而不是FileOutputStream)应该如何使用write 方法。

    针对您特定的write 方法调用

    outStream.write(buffer, 0, length);
    

    它的意思是:“写出buffer的内容到流outStream,从buffer[0]开始,下一个length字节”。

    第二个和第三个参数是指数组的边界。该方法会将buffer[0] 写入buffer[length - 1]。并且由于您一次又一次地从inStream 读取(参见while 循环的头部),buffer 的内容将被来自该输入流的连续字节填充。生成的操作是这里的文件副本。

    【讨论】:

      【解决方案2】:

      write()方法的最简单形式是write( byte[] buffer );它将整个缓冲区写入输出流。

      但是,通常情况下我们不想写入整个缓冲区,而只想写入其中的一部分。这就是write( byte[] buffer, int offset, int length ) 存在的原因。

      您提供的代码使用write() 方法的这种变体,因为缓冲区并不总是满的,因为read() 调用并不总是读取整个缓冲区,它会读取length 字节数。

      在您发布的代码中,每次调用 read() 方法时的偏移量为 0,这意味着它从输入流中读取字节并将它们存储到从偏移量 0 开始的缓冲区中。因此 @987654328 @ 方法还需要开始获取字节以从缓冲区的偏移量零开始写入输出流。这就是为什么要写入的偏移量为零的原因。

      但是,如果你有一个包含 100 字节的缓冲区,而你只想写中间的 80,那么你会说write( buffer, 10, 80 )

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多