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");
}
}
我无法理解 write() 方法是如何工作的?当它第一次被调用时,它会将内容从 0 索引写入到字节数组的长度,但是当它第二次被调用时,它如何将新文本附加到前一个文本的末尾?它应该覆盖以前的内容,因为再次以 0 作为起始索引调用 write。如果我理解有误,请帮助我?
最佳答案
write 方法中的起始偏移量不是指 FileOutputStream
中的偏移量,而是指您写入的数组中的偏移量。
您可以阅读 in the documentation of OutputStream
(而不是 FileOutputStream
)应该如何使用 write
方法。
为您的特定编写
方法调用
outStream.write(buffer, 0, length);
意思是:“写出 buffer
的内容到流 outStream
从 buffer[0]
开始下一个 length
字节"。
第二个和第三个参数指的是数组的边界。该方法会将 buffer[0]
写入 buffer[length - 1]
。由于您一次又一次地从 inStream
中读取(请参阅 while
循环的头部),buffer
的内容将被连续的字节填充这个输入流。生成的操作是这里的文件复制。
关于java - write(byte[],int,int) 方法是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43716511/