so i have this code below in my MainActivity, after I call this method, it pop up Toast "file saved" but i could not locate this file to be sure it saves what i wanted to, anyone?
private void saveToFile(String data){
try {
outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath()+"/batteryLogFile.txt", true);
PrintWriter out = new PrintWriter(outFile);
out.println(data);
out.close();
//output = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/batteryLogFile.txt");
//output.write(data.getBytes());
//output.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}catch(FileNotFoundException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(java.io.IOException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I've finally found the file, issue was about that I was debugging this app on my real device and while it was debugging, somehow app hasn't been saving my file. When I disconnect my device from computer and re-run application again, everything was good and file was located on my SD card.
Related
I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)
Example of my code (I tried more variations):
try {
File dir = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(("some text").getBytes());
stream.close();
toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
//toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
You have to set the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in your AndroidManifest.xml file.
If you run your app on Android 6.0 or higher you have to request this permission at runtime.
Request App Permissions
I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.
I am trying to create a text file in android internal storage but I am unable to do that. Can someone please tell me what am I doing wrong?
String append = "some data";
try {
FileOutputStream fileout=openFileOutput("fortify_profile.txt", Context.MODE_PRIVATE);
fileout.write(append.getBytes());
fileout.close();
Toast.makeText(getApplicationContext(), "Profile Created", Toast.LENGTH_LONG);
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not create Profile", Toast.LENGTH_LONG).show();
}
Every where I looked same method has been given to create a file on android internal storage but
mine is not working. Please help
Your code is correct and I hope that is creating file also. But you are not checking it in proper location. Go to data>data>your_package_name>files>fortify_profile.txt and that file should be there.
I'm trying to create a directory, and i'm checking whether it is created successfully or not but displaying a text on the screen, but nothing to be displayed.
Java code:
public void createDirectory() {
try {
String strDirectory = "test";
boolean success = ( new File(strDirectory)).mkdir();
if (success) {
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "error occured", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
Log.e("Error", "Error creating directory");
}
}
put .show() end of Both Toast....
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created",
Toast.LENGTH_SHORT).show();
Did you add uses-permission write external storage to your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I actually don't know where it's trying to create the directory since you are not qualifying the entire path. what are you trying to do?
If you are trying to create it on the SD card, do this,
File f = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
http://developer.android.com/reference/android/os/Environment.html
Note that this file will be readable by all apps.
If you are trying to create a file that's private to the app, do this,
OutputStream os = context.openFileOutput("myfile.txt");
http://developer.android.com/reference/android/content/Context.html
Note that this method is reserved for small files as it uses the internal storage which is limited on many devices.
Finally, always print the stack trace,
Log.e("mytag", "some message", e);
9 times out of ten, this will point you directly to the problem.
I have a strange problem I've come across. My app can write a simple textfile to the SD Card and sometimes it works for some people but not for others and I have no idea why.
For some people, it force closes if they put some characters like ... in the File and such. I cannot seem to reproduce it as I've had no troubles but this is the code which handles the File writing. Can anyone think of something that may lead to problems or a better to way to do it?
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();
}
}
You can use this method to check de sdCard state. Change the toast dialog to you language:
** Care with MEDIA_MOUNTED_READ_ONLY. In no need write in the SDCard and i return true **
public static Boolean comprobarSDCard(Context mContext) {
String auxSDCardStatus = Environment.getExternalStorageState();
if (auxSDCardStatus.equals(Environment.MEDIA_MOUNTED))
return true;
else if (auxSDCardStatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
Toast.makeText(
mContext,
"Warning, the SDCard it's only in read mode.\nthis does not result in malfunction"
+ " of the read aplication", Toast.LENGTH_LONG)
.show();
return true;
} else if (auxSDCardStatus.equals(Environment.MEDIA_NOFS)) {
Toast.makeText(
mContext,
"Error, the SDCard can be used, it has not a corret format or "
+ "is not formated.", Toast.LENGTH_LONG)
.show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_REMOVED)) {
Toast.makeText(
mContext,
"Error, the SDCard is not found, to use the reader you need "
+ "insert a SDCard on the device.",
Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_SHARED)) {
Toast.makeText(
mContext,
"Error, the SDCard is not mounted beacuse is using "
+ "connected by USB. Plug out and try again.",
Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_UNMOUNTABLE)) {
Toast.makeText(
mContext,
"Error, the SDCard cant be mounted.\nThe may be happend when the SDCard is corrupted "
+ "or crashed.", Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_UNMOUNTED)) {
Toast.makeText(
mContext,
"Error, the SDCArd is on the device but is not mounted."
+ "Mount it before use the app.",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
Are you checking that the external storage is writeable? If not then try using...
Environment.getExternalStorageState()
This will tell you if the SD card is mounted and you can also check if it's writeable. That's all I can think of to suggest at this point.
I just found out that in my case, i was missing adding <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in Manifest file.
Cheers,
wahib
For all fellow newbies out there debugging on an actual device via USB: Don't forget to unplug the USB cable from your dev PC, like I did. When USB is connected the SD card is unavailable. Happy file writing...
This is not correct on all phones/ROM builds. CMod7 and MIUI ROMS both allow you to set whether the SD card is mounted or not when plugged into PC, depending on your settings the above may hold true. Best to check.
I usually use PrintWriter rather than FileWriter. I don't know if it would solve your issue but it's of a higher level so it may take care of more things than a simple FileWriter.
I'm lost here.
I create files using this (stripped) code :
File dir = getBaseContext().getDir(dirPath, MODE_WORLD_WRITEABLE);
try {
File file = new File(dir, fileName);
FileOutputStream fous = new FileOutputStream(file);
fous.write(data);
fous.flush();
fous.close();
long l = file.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
I can verify with logcat that my file seems to be created (it has a not null lenght). But I cannot see it when I connect my android device to my PC.
So... where is my file ? Is it hidden ? Erased ?
EDIT : I'm now trying to write on the SDCard specifically, using this :
File root = Environment.getExternalStorageDirectory();
File jpegFile = new File(root.getAbsolutePath() + "/myApplication/" + filePath);
try {
jpegFile.mkdirs();
FileOutputStream fous = new FileOutputStream(jpegFile);
fous.write(data);
fous.flush();
fous.close();
Log.i("PpCameraActivity", "File written : " + jpegFile.getAbsolutePath());
Toast.makeText(getBaseContext(), "File written : " + jpegFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
long l = jpegFile.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
But I get a FileNotFoundException on the FileOutputStream creation...
OK found it.
Not an Android problem but just my error (not the first time) : mkdirs must be applied to the parent file, not the file I want to write...
So, for people interested :
Access the sd card using
File root = Environment.getExternalStorageDirectory();
Don't forget to require this permission
WRITE_EXTERNAL_STORAGE
Then make, as usual, mkdirs and file creation.
And don't forget : the android device cannot write on the sdard while it is mounted on you PC.
You probably aren't writing to the SD card, and the SD contents are all you can see from a USB connection.
Try something like this: http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html (just the first thing that came up when I searched for "Android write to SD card").