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 方法中的起始偏移量不是指FileOutputStream
中的偏移量,而是指从中写入的数组中的偏移量。
您可以在OutputStream
(而不是FileOutputStream
)文档中阅读如何使用write
方法。
对于您的特定write
方法调用
outStream.write(buffer, 0, length);
它的意思是:"写出buffer
的内容,从接下来的length
字节buffer[0]
开始流式传输outStream
"。
第二个和第三个参数引用数组的边界。该方法将buffer[0]
写入buffer[length - 1]
。而且由于您一次又一次地从inStream
读取(参见while
循环的头部),因此buffer
的内容将填充来自此输入流的连续字节。生成的操作是此处的文件副本。
write()
方法最简单的形式是write( byte[] buffer )
;它将整个缓冲区写入输出流。
但是,通常情况下,我们不想写入整个缓冲区,而只想写入其中的一部分。 这就是write( byte[] buffer, int offset, int length )
存在的原因。
您提供的代码使用write()
方法的此变体,因为缓冲区并不总是满的,因为read()
调用并不总是读取整个缓冲区,它会读取length
字节数。
在您发布的代码中,每次调用read()
方法的偏移量为 0,这意味着它从输入流中读取字节,并将其存储到从偏移量 0 开始的缓冲区中。 因此,write()
方法还需要开始提取字节以从缓冲区的偏移量零开始写入输出流。 这就是为什么要写入的偏移量为零。
但是,如果您有一个包含 100 个字节的缓冲区,并且您只想写入中间的 80 个字节,那么您会说write( buffer, 10, 80 )
.