output.flush();
时间: 2024-05-24 11:11:27 浏览: 5
The method output.flush() is used to flush the output stream. When we write data to an output stream, the data is not immediately written to the destination. Instead, it is stored in an internal buffer until the buffer is full or until the flush() method is called.
The flush() method forces any buffered data to be written to the output stream immediately. This is useful when we want to ensure that all data has been written before closing the stream or before performing some other action that requires the data to be written.
In summary, calling output.flush() ensures that any buffered data is immediately written to the output stream.
相关问题
import java.io.*; public class CopyFile { public static void main(String[] args) throws Exception{ FileInputStream input = new FileInputStream("src/text/text.txt"); //将复制的数据写到 src/text/text1.txt FileOutputStream output = [代码 1] ; byte[] b = new byte[10]; int len = 0; //利用输入流读取数据放入 b 中,读取的字节数记为 len //读到文件末尾则结束 共 7 页 第 5 页 while( [代码 2] ) { System.out.print(new String(b)); //将数组 b 从下标为 0 开始、len 结束,写出到输出流中 [代码 3] ; } output.flush(); //关闭输出数据流 [代码 4] ; input.close(); } }
以下是代码的完整版本,其中 [代码 1]、[代码 2]、[代码 3]、[代码 4] 需要填写相应的代码:
```java
import java.io.*;
public class CopyFile {
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream("src/text/text.txt");
FileOutputStream output = new FileOutputStream("src/text/text1.txt");
byte[] b = new byte[10];
int len = 0;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
System.out.print(new String(b, 0, len));
}
output.flush();
output.close();
input.close();
}
}
```
- [代码 1] 的填写:
```java
FileOutputStream output = new FileOutputStream("src/text/text1.txt");
```
- [代码 2] 的填写:
```java
(len = input.read(b)) != -1
```
- [代码 3] 的填写:
```java
output.write(b, 0, len);
```
- [代码 4] 的填写:
```java
output.close();
```
outputstream.flush()
The flush() method in OutputStream class flushes the buffered output stream. It forces any buffered output bytes to be written out to the underlying output stream.
In other words, it is used to ensure that all the data that has been written to the output stream is actually sent out and not sitting in some internal buffer.
Here is an example of how to use the flush() method:
```java
OutputStream os = new FileOutputStream("output.txt");
os.write("Hello World".getBytes());
os.flush();
os.close();
```
In the above example, we are creating a FileOutputStream object and writing a string "Hello World" to it. After writing the data, we call the flush() method to ensure that all the data is sent to the file. Finally, we close the output stream.