I want to create a textfile on my sdcard. I found lots of codesamples and tried them. None of them responded any Exception so i expected them to work, but when I was exploring my sdcard, I could not find a textfile.
Here is the attempt I am trying:
try {
File sdcard = Environment.getExternalStorageDirectory();
File myFile = new File(sdcard,"text.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(encodedString); // this is a long string
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"written to: "+myFile.getAbsolutePath(),
Toast.LENGTH_SHORT).show();
Here is what the Toast is telling me:
What I expect: "written to: /sdcard/text.txt"
What I get: "written to: /storage/emulated/0/text.txt"
Why is the app not saving the textfile as intended onto the sdcard and what do I have to change in order to make it do it?
getExternalStorageDirectory() does not necessary return /sdcard directory. See here Environment.getExternalStorageDirectory does not return the path to the removable storage
Related
I'm trying to write to a cache file.
Uri path1 = Uri.parse("content://package.name/cache");
File myFile = new File(path1.getPath(),"results.csv");
final boolean newFile = myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Added storage permission in Manifest.
Error I/ExternalStorageDemo: Save to: content://package.name/cache/results.csv W/System.err: java.io.IOException: Permission denied
Use Context.getCacheDir() to get applications Internal cache files dirctory
Like This:
File myFile = new File(context.getCacheDir(),"results.csv");
If your device is working on Android 6 or higher have you already requested runtime permissions?
See https://developer.android.com/training/permissions/requesting.html for more details.
I'm trying to write a text file in android's internal storage and browse through connecting it to a PC via usb. Now, I used the following code which worked fine for old devices with SD cards.
public void writeToFile(String stringToBeWritten)
{
final File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DCIM + "/Target Folder/"
);
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, "MyFile.txt");
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(stringToBeWritten);
System.out.println("Written Successfully");
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I've been surfing for a solution a while and tried a lot of thing to get my job done. All the solutions out there, to store the file internally but unable to browse.
Any ideas how to write my files on internal phone storage? I'd highly appreciate any help/suggestions. Thanks.
Please help...
I have created a text file in the first Activity of my App, which is all working fine.
In My next Activity, i want to append to the text file.
But when i try to append the catch throws up the following error..
mnt/scard/PatRecords/testfile.txt contains a file seperator
And nothing is added to the file.
my code for appending is..
try {
File directory = new File
(Environment.getExternalStorageDirectory().getPath()+"/PatRecords");
FileOutputStream fOut = openFileOutput(directory.getPath()+"/"+FileName$, MODE_APPEND);
OutputStreamWriter OutWriter = new OutputStreamWriter(fOut);
OutWriter.write(TestNo$+"\n");
OutWriter.write(Date$+"\n");
OutWriter.close();
fOut.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
Error=1;
}//End of try/catch
I have tried removing the seperators etc but still doesn't work, and as far as i can see
the path shown in the catch error is correct...?
openFileOutput() is for opening files in your program data folder, which is located on the internal memory, you may only supply the file name, not the path, hence the complain mnt/scard/PatRecords/testfile.txt contains a file separator.
if you want to open files on the SD card, you have to use FileOutputStream() or something like that:
File of = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
I have an application that creates a configuration file and a log file. I stored these in the external storage, but when I try it in my android emulator it doesn't work because the external storage isn't writable. If this happens, where should I store the files?
This is my code:
private void createConfigurationFile(){
File ssConfigDirectory =
new File(Environment.getExternalStorageDirectory()+"/MyApp/config/");
File file = new File(ssConfigDirectory, mUsername+".cfg");
if(!file.exists()){
try{
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)){
ssConfigDirectory = new File("PATH_WHERE_I_SHOULD_STORE_IT");
}
File ssLogDirectory = new File(ssConfigDirectory+"/SweetSyncal/log/");
ssLogDirectory.mkdirs();
ssConfigDirectory.mkdirs();
File outputFile = new File(ssConfigDirectory, mUsername+".cfg");
FileOutputStream fOut = new FileOutputStream(outputFile);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
writeFile(osw);
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
If the file isn't too big you can save it in the device's Internal Storage.
To access the Internal Storage you can use the following method:
FileOutputStream openFileOutput (String name, int mode)
(You need an instance of Context to use it)
Example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
As to why the code you provided is not working then there are two possibilities:
You forgot to add the required permission (WRITE_EXTERNAL_STORAGE).
You'r emulator doesn't have an SD card enabled. Assuming you are using Eclipse you can enabled it in the AVD Manager. Just edit your AVD instance and type in the size of the SD card in the appropriate field. You should also add a hardware feature called SD Card Support and set it to TRUE.
There is a great article in the official Developer Guide which will tell you everything you need to know about storage in Android.
You can read it HERE
Using the data-storage page in the docs, I've tried to store some data to the SD-Card.
This is my code:
// Path to write files to
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory.
Can anyone tell me what I'm doing wrong?
I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".
Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Before reading or writing to SD card, don't forget to check the SD card is mounted or not?
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)