Can't see a file in Windows written by an Android app on SD card unless I “Force Close” the app

佐手、 提交于 2019-11-27 19:09:42
thiagolsilva

It´s necessary that you use the following code so that your archive will be shown in the file system of Windows or in the gallery of the phone.

You have two possibilities:

  1. It´s faster because Android updates only the file passed:

    MediaScannerConnection.scanFile(this, new String[]{"your path here</"}, null, null);

  2. It´s more expensive because Android will search all the files in the path passed. You can pass only the path of the folder to reduce the search of the files:

    context.sendBroadcast(
        new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                   Uri.parse("file://" + "path of the folder")));
    

Because a BufferedWriter object is a buffer, you need to flush() the buffer to force the content to be written to the output stream.

String file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Files/hello.txt";
BufferedWriter writer = new BufferedWriter(new FileWriter(file));   
writer.write(str+"\n");
writer.flush(); // force the buffer to actually dump its data to the stream
writer.close();

When you .write() using a buffer, always remember that the data will be held in the buffer until either the buffer is filled (and then automagically flush()ed) or you force the buffer to flush its data using the .flush() method of the buffer.

Additionally, the reason the file wasn't being written to correctly until you force-closed the application is because when you kill an application, one of the steps taken is to flush() all buffers associated with the application. That's why this was only happening when you force-killed it.

Note: Bear in mind that this is the default behavior of most kinds of buffered streams in many different languages.

Gregory Cone

Windows 7 did have issues seeing files when connected through the USB connection. The workaround for me was using a GNU/Linux distribution.

Using a terminal app, there is a difference where root:root files are viewable on Explorer, but no other owners.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!