FileOutputStream vs OutputStream, why and when?
So, depending on the question you are trying to ask, there are two different answers here. (1) Is there a difference between the two OutputStream objects that have been created in your example? And (2) is there a difference between the two Object types and when should each be used?
(1)
ObjectStream os = new FileObjectStream(File file);
and
FileObjectStream fos = new FileObjectStream(File file);
are no different.
Because FileObjectStream is a subclass of the abstract ObjectStream, the Object can be created using the subclass constructor and will inherit all subclass functionality.
(2)
OutputStream is an abstract class which should be sub classed, by an Object such as FileOutputStream, so that the write(byte[] b)
call may be overridden and any functionality specific to the output sink may be added. More simply, FileOutputStream (and subclasses of OutputStream like it) "is a" OutputStrem object, but OutputStream is not a FileOutputStream object.
Lauro182
Java developer, I like challenges and I love learning new things. It feels so good when things come together. Understanding things and not just making them work, is the way I like doing things.
Updated on November 28, 2022Comments
-
Lauro182 over 1 year
So, you can save a form file through several methods, I guess, I use 2, but I never really know when to use which. I have these 2 pieces of codes that do the same:
1-This writes my form file to specified path.
FormFile archivo = myForm.getArchivo(); File newFile = new File(path, archivo.getFileName()); FileOutputStream fos = new FileOutputStream(newFile); fos.write(archivo.getFileData()); fos.flush(); fos.close();
2-This does too.
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();
So, my question here is, what's the difference between the 2 of them, and when should I use which?
-
Vishy almost 9 yearsThe first example is harder to maintain e.g. to make it a
BufferedOutputStream