FileOutputStream vs OutputStream,为什么以及何时?

Lau*_*182 0 java outputstream java-io

所以,你可以通过几种方法保存表单文件,我猜,我使用2,但我真的不知道何时使用哪个.我有两个相同的代码:

1 - 这将我的表单文件写入指定的路径.

FormFile archivo = myForm.getArchivo();
File newFile = new File(path, archivo.getFileName());
FileOutputStream fos = new FileOutputStream(newFile);
fos.write(archivo.getFileData());
fos.flush();
fos.close();
Run Code Online (Sandbox Code Playgroud)

2 - 这也是.

FormFile archivo = myForm.getArchivo();
InputStream in = archivo.getInputStream();
OutputStream bos = new FileOutputStream(path + "archivo.ext");

int byteRead = 0;
byte[] buffer = new byte[8192];
while ((byteRead = in.read(buffer, 0, 8192)) != -1) {
     bos.write(buffer, 0, byteRead);
}
bos.close();
in.close();
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是,它们中的两个之间有什么区别,我何时应该使用哪个?

小智 5

因此,根据您要问的问题,这里有两个不同的答案.(1)在您的示例中创建的两个OutputStream对象之间是否存在差异?(2)两种对象类型之间是否存在差异?何时应该使用哪种?

(1)

ObjectStream os = new FileObjectStream(File file);
Run Code Online (Sandbox Code Playgroud)

FileObjectStream fos = new FileObjectStream(File file);
Run Code Online (Sandbox Code Playgroud)

没有什么不同.

因为FileObjectStream是抽象ObjectStream的子类,所以可以使用子类构造函数创建Object,并继承所有子类功能.

(2)OutputStream是一个抽象类,应该由诸如FileOutputStream之的对象进行子类化,以便write(byte[] b)可以覆盖调用,并且可以添加特定于输出接收器的任何功能.更简单地说,FileOutputStream(和OutputStream的子类一样)"是一个"OutputStrem对象,但OutputStream不是FileOutputStream对象.