简体   繁体   中英

openFileOutput() method vs FileOutputStream() constructor

Why in Android one should use openFileOutput() method instead of FileOutputStream() constructor?

Would the mode type as a second param of openFileOutput() be the only "respectful" reason for all the cases?

FileOutputStream fos;
fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
fos = new FileOutputStream("test.txt");

openFileOutput is specifically used for file writing into internal storage and disallow writing to external storage. However, FileOutputStream allows you to write to both internal and external storage as well. From my experience, you can create a directory with ease using FileOutputStream in internal storage. You can also set a mode using FileOutputStream as the 2nd parameter in one of its constructor . Example of how you write to internal storage using FileOutputStream in append mode:

 File filedir = new File(MyApplication.getAppContext().getDir("DirectoryNameYouWant"));
File filename = new File("FilenameYouWant");
FileOutPutStream fOut=new FileOutputStream(new File(filedir,filename),true);

Would the mode type as a second param of openFileOutput() be the only "respectful" reason for all the cases?

Another difference is that openFileOutputStream opens / creates a file in the the device's "internal" storage. By contrast FileOutputStream allows use of both internal and external storage.

A third difference is that openFileOutputStream writes files in the context of the current application, while FileOutputStream can write in any context ... modulo possible permissions issues.

(Both versions can open files in append mode. That is not a point of difference.)

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM