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.
Related
I am going to create one .pdf file and I am getting file not found exception. I have written WRITE_EXTERNAL_STORAGE permission for that in AndroidManifest.xml file and also provided runtime permission for Marshmallow device.
Below is my code:
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot + "xyz/", pdfFilename);
if (!file.exists()) {
file.mkdir();
}
OutputStream fileOutput = new FileOutputStream(file);
docWriter = PdfWriter.getInstance(doc, fileOutput);
Can you please get me out?
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
I try this file writer/reader code segment for test:
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(("test").getBytes());
outputStream.close();
File file = new File(getExternalFilesDir(null), "LM/lm_lisdat_01.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
In the 4. row i got this error message below but the "lm_lisdat_01.txt" file was created in LM directory:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/hu.abisoft.lm/files/LM/lm_lisdat_01.txt: open failed: ENOENT (No such file or directory)
Can help anyone for answer this (i think simple) question? I'm newby in Android. Thank you!
You are creating the file in one directory and trying to open it for input in another.
Environment.getExternalStorageDirectory() is /storage/emulated/0
getExternalFilesDir(null) is /storage/emulated/0/Android/data/hu.abisoft.lm/files
Use the same directory for file creation and input.
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
Please see changes. Your path was wrong.
And also check whether file exists or not.
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(("test").getBytes());
outputStream.close();
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");//changes here
if(file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
}
I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
I may be way off here, but I am trying to download a file and store it in the downloads folder on my phone. I am getting a "java.io.FileNotFoundException" error, because the file doesn't exist, because I'm trying to download it...what am I doing wrong?
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
FileOutputStream fos = new FileOutputStream(outputFile);
This fails, with the following:
java.io.FileNotFoundException: /mnt/sdcard/download/downloadFile (Permission denied)
I am using the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions....
Please try following updated code,
String PATH = Environment.getExternalStorageDirectory() + "/download";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
if ( !outputFile.exists() )
{
outputFile.create();
}
FileOutputStream fos = new FileOutputStream(outputFile);
There is a "/" after the download. This way Android is thinking that you are creating Recursive Directory. While using mkdirs(), you can not create recursive directories.
You can also check my answer for same in Java ME here.
Add Permission to write external memory in your Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here you want to make directoy?
it there is already folder of download than use this code directly.
// create a File object for the parent directory
File Directory = new File("/sdcard/download/");
Directory.mkdirs();
// create a File object for the output file
File outputFile = new File(Directory, downloadFile);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change