How to save file on external SDCARD on android MotorolaARTIX2 device? - android

I would like to save a file on external SdCard.I have implemented an application for save a file on external sdcard.But my Android MotorolaARTIX2 device contains internal sdcard.When i am trying to save file on external sdcard it always saving to internal sdcard in my device.
I have implemented my application as follows:
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File file = new File(root, "myfile.txt");
FileWriter gpxwriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
} catch (IOException e) {
Log.e("Exception", "Could not write file " + e.getMessage());
}
From the above code my application always saving myfile.txt file on internal sdcard but not external sdcard-ext.And my application is support all devices with same code.
How can i save myfile.txt on sdcard-ext(external) not on sdcard(internal) in my device?
please any body help me....

Motorola has an API for this. Look here: http://developer.motorola.com/docs/motorola-external-storage-api/ But that's not a good generic solution. You probably need to scan the filesystem for a more generic solution that will work on all devices.

Take a look at the answer from this question, especially the one from Baron

Related

How to upload a file and read the contents of a file in android

I am working on an android application where I want users to upload a file and I want to read the contents of uploaded file and display it . I have been reading files from SD card but I now I need the user to upload a file . I searched a lot but I didn't get any solution for it.
My code for reading the file from SD card
File file = new File(dir, "/tounzip/b.txt");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataInputStream input = new DataInputStream(fileInputStream);
Its reading the file contents successfully but Is there any way to make the user upload the file and read the contents from it ? Any help would be great !! Thanks !!
Android file chooser
You require a file picker/file chooser.
Logic is you read the stream and save the stream in your app sandbox (app's memory i.e. /data/package..) then do whatever you want from there.
If file size is small then even a in-memory implementation will help.

How can I write a file to a folder of the internal storage on Android?

I have written a method which creates a file and writes data to the file and stores in the internal storage. When I get the absolute path or path of the file [I have added log messages to experiment with the operations on the File], it shows me that the file is getting created under the root directory and its under the /data/data/mypackagename/files/filename.txt. Nevertheless, I could find these folders on the DDMS where I could find the file which has been created by the method which I have written. But I am unable to open that file too as I don't have permissions.
When I look at my Android device, I can't find these directories. I looked up on stack overflow and some have answered that the /data/data folders in the internal storage are hidden and to access them I have to root the device which I don't want to do.
Next approach: There is a folder called as MyFiles on the android device [I am using Galaxy Tab 4 running Android 4.4 for testing]. Under this folder there is Device Storage directory which has various folders like Documents, Pictures, Music, Ringtones, Android, etc, etc.. So, the apps like camera, spread sheet apps, are able to write or save pictures into the pictures folder or txt files in the documents folder. Similarly, how could I write the file which I am creating in the function to the Documents folder or any other folder which could be accessible over the device. Please help me how could I do it, any help is appreciated.
The following is the code which I have written:
public void addLog(String power_level){
// creates a logFile in the root directory of the internal storage of the application.
// If the file does not exists, then it is created.
Log.d("AppendPower", "In addLog method");
//File logFile = new File(((Context)this).getFilesDir(), "logFile.txt");
File logFile = new File(getFilesDir(), "logFile.txt");
Log.d("FilesDir Path", getFilesDir().getAbsolutePath());
Log.d("FilesDir Name", getFilesDir().getName());
Log.d("Path on Android", logFile.getPath());
Log.d("Absolute Path on Android", logFile.getAbsolutePath());
Log.d("Parent", logFile.getParent());
if(!logFile.exists()){
try{
logFile.createNewFile();
}catch(IOException io){
io.printStackTrace();
}
}
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
writer.write("Battery level reading");
writer.append(power_level);
Log.d("Power_Level in try", power_level);
writer.newLine();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
As you have figured out writing to root directories in Android is impossible unless you root the device. Thats why even some apps in Play-store asking for root permissions before installing the app. Rooting will void your warranty so i don't recommend it if you don't have serious requirement.
Other than root directories you can access any folder which are visible in your Android file manager.
Below is how you can write into sd with some data - Taken from : https://stackoverflow.com/a/8152217/830719
Use these code you can write a text file in SDCard along with you need to set permission in android manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
.
1) If your purpose is debugging, you may just write to the /sdcard/. It always works.
2) Again, if your purpose is debugging, you may try to set read permissions on your app's directories. A while ago it worked for me on some Android devices (but did not work on at least one device).
Add this permission in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then use this shortest recipe:
try
{
FileOutputStream fos =
openFileOutput("myfile.txt", getApplicationContext().MODE_PRIVATE);
fos.write("my text".getBytes());
fos.close();
}
catch (Exception exception)
{
// Do something, not just logging
}
It will be saved in "/data/data/my.package.name/files/" path.

Android saving file to SD Card, not internal storage

I know there have been questions about this, but for some reason nothing seems to work for me.
I'm trying to get 2 text files to save to the SD card from my app. It correctly creates the directory and the files, but always to the Internal Storage, never the External Storage. I do have the permissions in place as well in the Manifest.
try {
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard.getAbsolutePath() + "/rlgl");
myFile.mkdir();
// myFile.createNewFile();
String newLine = System.getProperty("line.separator");
File file = new File(myFile, "rlgls.txt");
if(file.exists()) {
} else if (!file.exists()){
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < 30; i++) {
myOutWriter.append("0.0" + newLine);
}
myOutWriter.close();
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
This is the code that I am using. I've followed directions from other Stackoverflow responses but it never goes to the SD Card. Is there something I'm doing wrong? Also a follow up question is there a way for me to use the above code in order to make the files invisible to the user. They should have no reason to open them. Thanks in advance.
It correctly creates the directory and the files, but always to the Internal Storage, never the External Storage
No, it places them on external storage. What the user sees as internal storage is what the developer sees as external storage. Internal storage is accessed via methods like getFilesDir(). And none of those are removable storage, such as some form of SD card.
Also a follow up question is there a way for me to use the above code in order to make the files invisible to the user. They should have no reason to open them.
Then put them on internal storage.
my app can't read/write from/to the files when there is a "." in front of their names
I find that very difficult to believe. The . prefix makes them not show up by default in some file browsers, but that's it. Users can get to them (if they are on external storage), and apps can get to them (subject to the same rules as any other files, those without a leading .).

File creation in SD card not working

I am trying to create a file and store it in SD Card to be used as an input for some processing for an apps.
After searching for a while, I got this code which can create a file in SD card.But after running this,I couldn't see any file created in my SD card. Can anyone please help me what I am missing here.
BufferedWriter out = new BufferedWriter(new FileWriter(FileDescriptor.err));
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File perffile = new File(root, "samplefile.txt");
FileWriter perfwriter = new FileWriter(perffile, true);
out = new BufferedWriter(perfwriter);
}
} catch (IOException e) {
Log.e(TAG, "-Could not write file " + e.getMessage());
return;
}
If you want to add a file or folder or move application into your SD Card just do the following:
steps:
1) Open your Android application's source code file with a text or programming editor.
2) Browse to the location in the source code where you wish to call the function that writes a file to the device's external storage.
3) Insert this single line of code to check for the SD card:
File sdCard = Environment.getExternalStorageDirectory();
4) Insert these lines of code to set the directory and file name:
File dir = new File (sdcard.getAbsolutePath() + "/folder1/folder2");
dir.mkdirs();
File file = new File(dir, "example_file");
// The mkdirs funtion will create the directory folder for you, use it only you want to create a new one.
5) Replace "/folder1/folder2" in the above code with the actual path where you intend to save the file. This should be a location in which you normally save your application files. Also, change the "example_file" value to the actual file name you wish to use.
6) Insert the following line of code to output the file to the SD card:
FileOutputStream f = new FileOutputStream(file);
Finally step 7:
Save the file, then compile it and test the application using the Android emulator software or the device.
This will works!!! ;-)

Data directory has no read/write permission in Android

I m using Android 1.5 my data directory doesn't have the read/write permissions
System.out.println("DAta can write??--->"+Environment.getDataDirectory().canWrite());
System.out.println("DAta can read??--->"+Environment.getDataDirectory().canRead());
So please suggest me how to provide permissions for the data directory.
What I'm trying to do is to create a file and add some content to it in the Data storage of the emulator like as below
private void writeToSDCard() {
try {
File lroot = Environment.getDataDirectory();
if (lroot.canWrite()){
File lfile = new File(lroot, "samplefile.txt");
FileWriter lfilewriter = new FileWriter(lfile);
BufferedWriter lout = new BufferedWriter(lfilewriter);
lout.write("XXXXXXXXXXXXXXXXXX");
lout.close();
}
} catch (IOException e) {
Log.e(m_cTAG, "Could not write file " + e.getMessage());
}
}
You shouldn't be looking at the Data Directory. This is a system directory in the phone's storage - usually /data - and your application will never have permission to write to it.
The directory your application should write files to is returned by the Context.getFilesDir() method. It will be something like /data/data/com.yourdomain.YourApp/files.
If you want to write to a file in the phone's storage use the Context.openFileOutput() method.
If you want the path to the SDCard then use Environment.getExternalStorageDirectory() method. To write to the SDCard you'll need to give your application the appropriate permissions by adding the following to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you're going to write to the SDCard you'll also need to check its state with the getExternalStorageState() method.
If you're storing small files to do with your application then these can go into the phone's storage and not the SD Card, so use the Context.openFileOutput() and Context.openFileInput() methods.
So in your code consider something like:
OutputStream os = openFileOutput("samplefile.txt", MODE_PRIVATE);
BufferedWriter lout = new BufferedWriter(new OutputStreamWriter(os));
you need to locate your save build location, sometimes its automatically located in the read-only area on your pc

Categories

Resources