I want to write something to a file. I found this code:
private void writeToFile(String data) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } }
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Perhaps the cleanest, most succinct solution to write a String to a File is through the use of the FileWriter. With this class, you pass its constructor the File object that you'd like to write to, and then you call its write method to write strings of data to the file.
fputs() is used to write a string to a file.
Writing a Fileint fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error.
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/
).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data) { // Get the directory for the user's public pictures directory. final File path = Environment.getExternalStoragePublicDirectory ( //Environment.DIRECTORY_PICTURES Environment.DIRECTORY_DCIM + "/YourFolder/" ); // Make sure the path directory exists. if(!path.exists()) { // Make it, if it doesn't exit path.mkdirs(); } final File file = new File(path, "config.txt"); // Save your stream, don't forget to flush() it before closing it. try { file.createNewFile(); FileOutputStream fOut = new FileOutputStream(file); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(data); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } }
[EDIT] OK Try like this (different path - a folder on the external storage):
String path = Environment.getExternalStorageDirectory() + File.separator + "yourFolder"; // Create the folder. File folder = new File(path); folder.mkdirs(); // Create the file. File file = new File(folder, "config.txt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With