Writing a file to external storage android FileNotFoundException - android

I want to write a file to external storage in android but get the FileNotFoundException. I have put the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
in my manifest and if I do a check like
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
it returns true. I have tried different solutions from questions from SO (Android saving file to external storage; Write a file in external storage in Android; Writing to external storage filenotfoundexception) but none seemed to work for me. Sorry for posting a duplicate question but Ive been searching for days and couldnt find an answer.
My Code is the following:
private void Writing(String erg) {
TextView one = (TextView) findViewById(R.id.e1);
File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "Test.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(erg);
pw.flush();
pw.close();
f.close();
one.setText("File created");
} catch (FileNotFoundException e) {
e.printStackTrace();
one.setText("Error1");
} catch (IOException e) {
e.printStackTrace();
one.setText("Error2");
}
}
The Textview one ends up with printing Error1.
I'll appreciate any help.

Related

How to delete a file from internal memory before replacing it

I would like to delete an internal file at runtime. When I download from an external server, the old version of the file (with the same name) is replaced, however I am unable to read it. I think that I need to delete the previous file before downloading the new version. Here is an example of what I have tried so far:
try {
FileOutputStream fos = getApplicationContext().openFileOutput("mytext.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(pictosFile.getAbsolutePath()).getBytes());
Log.e("mytextfile",""+getStringFromFile(pictosFile.getAbsolutePath()));
progressDialog.cancel();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
This allows me to save the file into internal memory, but I am unsure about how to delete the previous file before writing the new version.
If you need to ensure that the file is overwritten, i.e. delete an old copy before saving a new version, you can use the exists() method for a file object. Here is an example showing how to delete an old version of an image file before writing a new file with the same name in a nested directory:
// Here TARGET_BASE_PATH is the path to the base folder
// where the file is to be stored
// 1 - Check that the file exists and delete if it does
File myDir = new File(TARGET_BASE_PATH);
// Create the nested directory structure if it does not exist (first write)
if(!myDir.exists())
myDir.mkdirs();
String fname = "my_new_image.jpg";
File file = new File(myDir,fname);
// Delete the previous versions of the file if it exists
if(file.exists())
file.delete();
String filename = file.toString();
BufferedOutputStream bos = null;
// 2 - Write the new version of the file to the same location
try{
bos = new BufferedOutputStream(new FileOutputStream(filename));
Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.PNG,90,bos);
bmp.recycle();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
try{
if(bos != null)
bos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
You must also ensure that you have read / write access to memory, make sure that you ask the user for these permissions at run time and have the following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Android Append text to file not working even if fileOutputStream appending mode setted to TRUE

I am trying to append text into a file stored in emulated/0/.. folder (external storage without SD Card)
FileOutputStream fileOutputStream = new FileOutputStream(capturesFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
String data = "my data";
writer.append(data);
writer.close();
fileOutputStream.flush();
fileOutputStream.close();
This code is not working, I really do not understand why. Is the emulated location is a problem (stupid question but at this point...) I already tried many ways without any positive solution.
Is someone have an idea about this issue.
Use this code
try {
FileWriter fw = new FileWriter("path/of/file",true);
fw.write("myData");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
First make sure you've given the required permission to write a file and that would be -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file and
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
in your activity.
Second please check your directory path. There might be some chances that you are using a wrong path. Easiest way to get a direct path for the Internal Storage is -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data" + getApplicationContext().getPackageName();
File file = new File(path + "/File.txt");
You can use this method as per your requirement to write a file -
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.append("My Data");
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

getting a FileNotFoundException using the following code

I am trying to create a logfile of RSSI values and RSSI values once a filter has been applied. I do not want to use the android logfile. I want to use a text file that I can export to excel. This is the code that I have written. I am new to android, but have some java experience.
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d("MainActivity", "MEDIA_MOUNTED is true");
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "RSSI.txt");
try {
pw = new PrintWriter(new FileWriter(file), true);
pw.print(beacon.getRssi());
pw.print(kalman.kalman(rssis));
pw.println();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
you can try creating a new file if it doesn't exist
if(!file.exists())
{
file.createNewFile()
// you can start writing to file from here.
}
make sure to add permission to read and write from the external storage in the manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Unable to write to external SD Card in Android

I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.

android error trying to write to external SD

I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.

Categories

Resources