问题
I am writing an App, in which I would like to append a text file, as various user actions happen. I would like the text file to be located in internal memory. I would like the text file to also be visible under Windows Explorer, if the user connects the tablet with a usb cable.
I have looked at many examples, and have been able to write a text file to internal memory, but I can not seem to make the file visible in File Manager.
Does anyone know if it is possible to write a text file to internal memory, and have it visible to the user under Windows Explorer? Or do I need to use an SD card instead of internal memory?
回答1:
I would like the text file to be located in internal memory.
"Internal memory" does not have a lot of meaning from a programming standpoint.
I would like the text file to also be visible under Windows Explorer, if the user connects the tablet with a usb cable.
That would be external storage.
but I can not seem to make the file visible in File Manager.
Use MediaScannerConnection and its scanFile() method to tell the MediaStore about the file. That will at least allow the file to be visible to an MTP client like Windows' explorer windows. Note that you may need to "refresh" or "reload" in that explorer window to get Windows to pick up the new file.
回答2:
Ok, I have this working as I want it to, now. It will save the text file (and append it each time it is written) to the non-removable DOWNLOAD folder of a tablet/phone. My target was a minimum SDKversion of 16 (4.1.2 Jellybean).
I will post the code below, for anyone else who gets confused by this issue.
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "mytextfile.txt");
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("the text I want added to the file");
myOutWriter.close();
fOut.close();
Toast.makeText(this,"Text file Saved !",Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
//do something if an IOException occurs.
Toast.makeText(this,"ERROR - Text could't be
added",Toast.LENGTH_LONG).show();
}
You will also need the following line added to the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You will need to import:
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.File;
来源:https://stackoverflow.com/questions/32610171/saving-a-text-file-to-public-internal-memory-location-in-android