FileNotFoundException : Can't Open file, file not found in Android - android

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?

Related

Creating a directory on external sd card that will have a text file written to it

I am trying to create a folder on my external SDcard that will contain a text file that I can pull off my phone from my PC and read it.
I have pieced together a snippet that I believe should work, but I cannot find the folder that is supposedly being created.
File path = Environment.getExternalStorageDirectory();
File dir = new File(path.getAbsolutePath() + "/iptestdata/");
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = new SimpleDateFormat("yyyyMMddHHmmss'.txt'").format(new Date());
final File file = new File(dir, fileName);
As I am stepping though the debugger in Android Studio, I see the path being created and stored in dir is /storage/emulated/0/iptestdata, and I see the file name appearing in the format that I requested, but I cannot find the file via File Explorer in Windows. How can I fix this?
If you create File and store into storage Directory you want to call mkdirs()
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + " /dir - name /");
dir.mkdir();
File file = new File(dir, "File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();
Please check the Directory is created or not the following method
public static boolean canWriteOnExternalStorage() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.v("Activity", "Yes, can write to external storage.");
return true;
}
return false;
}
Add Permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

FileNotFoundException: /storage/emulated/0/Android

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)));
}

Android Subfolder sdcard

I create a folder called "res" inside sdcard
File f = new File(Environment.getExternalStorageDirectory() + "/res/");
f.mkdirs();
The folder is successfully created.
But when I try to create a file within the folder does not work.
String string = "hello!";
File file = new File(Environment.getExternalStorageDirectory() + "/res/","test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
LOGCAT
java.io.FileNotFoundException: /mnt/sdcard/res/test.txt (Not a directory)
The call to new File() doesn't actually create the file. You need to check if the file exists by using file.exists(). If it doesn't, you must create the file by calling file.createNewFile(). See this answer for sample code: https://stackoverflow.com/a/7012122/379245

Writing File in External SD card in android

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())));

Android - downloading file, java.io.FileNotFoundException

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

Categories

Resources