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
Related
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
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Ok so the above code creates a file in the internal storage and writes something into it. My question is, where can I find and open this file in Eclipse? I want to see its contents and edit it manually. Or I may want to include my own file and read its contents.
My question is, where can I find and open this file in Eclipse?
Using the file manager in the DDMS perspective, for the default user account on an emulator, go to /data/data/your.application.id.goes.here/files, substituting in the package from your manifest where I have your.application.id.goes.here.
I'm trying to recreate a simple text editing Android app and so far I have this code to save the file:
String filename = "myfile";
String content = edit.getText().toString();
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename,
Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However I have no idea where in the internal storage this is being saved. How can I access/look at this directory to confirm the file has actually saved. I cant seem to find the file in File explorer in Eclipse (Heck, I can't even find the app name).Also, how would I go about loading this file once it is located? Thanks.
openFileOutput(filename,
Context.MODE_PRIVATE); is application private directory output stream api. Your file will saved in your /data/data/your_packagename directory.
I have a little issue with creating folders for my application in Internal Memory. I'm using this piece of code :
public static void createFoldersInInternalStorage(Context context){
try {
File usersFolder = context.getDir("users", Context.MODE_PRIVATE);
File fileWithinMyDir = new File(usersFolder, "users.txt"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
File dataFolder = context.getDir("data", Context.MODE_PRIVATE);
File fileWithinMyDir2 = new File(dataFolder, "data.txt"); //Getting a file within the dir.
FileOutputStream out2 = new FileOutputStream(fileWithinMyDir2); //Use the stream as usual to write into the file.
File publicFolder = context.getDir("public", Context.MODE_PRIVATE);
File fileWithinMyDir3 = new File(publicFolder, "public.txt"); //Getting a file within the dir.
FileOutputStream out3 = new FileOutputStream(fileWithinMyDir3); //Use the stream as usual to write into the file.
} catch(FileNotFoundException e){
e.printStackTrace();
}
}
So folders are created but in front of their name there is the beginning "app_" : app_users, app_data, app_public. Is there a way to create the folders with the name given by me? And another question : I want to first create folder Documents and than all other folders "Data, Public, Users" on it.... And the last question : How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Thanks in advance!
You can use this :
File myDir = context.getFilesDir();
String filename = "documents/users/userId/imagename.png";
File file = new File(myDir, filename);
file.createNewFile();
file.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(mediaCardBuffer);
fos.flush();
fos.close();
Is there a way to create the folders with the name given by me?
Use getFilesDir() and Java file I/O instead of getDir().
How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Use getFilesDir() and Java file I/O, such as the File constructor that takes a File and a String to assemble a path.
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)