我对flush和close方法感到困惑.在我的代码中,我总是关闭我的FileOutputStream对象.但我想知道如果我必须在这里使用flush方法,我可以在哪里使用它?
我将编写一个重复下载4或5个文件的项目.我将编写一个方法(用于下载文件),我的方法将循环并重复下载文件.我的方法将有这样的代码.
该close方法是否调用flush,或者在关闭之前是否必须使用flush?
try {
InputStream inputStream = con.getInputStream();
FileOutputStream outputStream = new FileOutputStream("C:\\programs\\TRYFILE.csv");
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch(Exception e) {
//
} finally {
outputStream.close();
inputStream.close();
}
Run Code Online (Sandbox Code Playgroud)
请注意,代码运行良好:它成功下载文件.但我不确定使用flush.
我在close()之前读了这个问题使用flush(),接受的答案是这只意味着你遵循模式.
就像BufferedWriter #close ()或FilterOutputStream.#close(),如果所有缓冲的Stream/Writer都会flush()在我们调用的时候调用它close(),如果我们(开发人员和将要审查代码的开发人员)都知道这一点,那么我们真的还需要这个吗?如果是的话,原因是什么?
import java.io. * ;
public class Ser {
public static void main(String args[]) {
try {
John myObj = new John("Sachin", "Cricket");
System.out.println(myObj);
FileOutputStream fos = new FileOutputStream("FileName");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myObj);
oos.flush();
oos.close();
} catch (Exception e) {
System.out.println("Expection" + e);
System.exit(0);
}
try {
John myObj2;
FileInputStream fis = new FileInputStream("FileName");
ObjectInputStream ois = new ObjectInputStream(fis);
myObj2 = (John) ois.readObject();
ois.close();
System.out.println("New Object" + myObj2);
} catch (Exception e) {
System.out.println("Expection" + e);
System.exit(0);
}
} …Run Code Online (Sandbox Code Playgroud)