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())));
Related
I have used this code for creating a file in my Phone's external storage. Please note that I've set the permissions for Read and Write in my Manifest file.
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
My LogCat is showing the below. I can't see the file 20170602.txt in that particular location. In my Download folder, there isn't any file with that name. Can anyone tell me where I went wrong.
D/tag: Directory: /storage/emulated/0/Android/data/com.pc.tab/files/Download
D/tag: File: /storage/emulated/0/Android/data/com.pc.tab/files/Download/20170605.txt
UPDATE:
I'm using MOTO G4 for running this app. I found the 20170602.txt file on Internal Storage.
File Manager --> `LOCAL` tab ( Upper right ) --> Internal Storage --> Android --> data --> com.pc.tab --> files --> Download --> 20170602.txt
It is important to separate the directory and the file itself
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
In your code you call mkdirs on the file you are want to write on, its an error because mkdirs makes your file be an a directory. You should call mkdirs for the directory only so its will be created if its not exist, and the file will be created automatically when you create new FileOutputStream object for this file.
Your code should look like this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.
I'm trying to write an image file into the public gallery folder in a specific directory but I keep getting an error that I can't open the file because its a directory.
What I have so far is the following
//set the file path
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
File outputFile = new File(path,"testing.png");
outputFile.mkdirs();
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Where directory is the application name. So all the photos saved by the application will go into that folder/directory, but I keep getting the error
/storage/sdcard0/Pictures/appname/testing.png: open failed: EISDIR (Is a directory)
Even if I don't try to put it in a directory and cast the variable path as a File like
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
I don't get the error however the photo is still not showing up in the gallery.
***Answer
The problem was that when I ran this code originally it created a DIRECTORY named testing.png because I failed to create the directory before creating the file IN the directory. So the solution is to make the directory first then write into it with a separate file like so
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + directory;
//directory is a static string variable defined in the class
//make a file with the directory
File outputDir = new File(path);
//create dir if not there
if (!outputDir.exists()) {
outputDir.mkdir();
}
//make another file with the full path AND the image this time, resized is a static string
File outputFile = new File(path+File.separator+resized);
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Note you may need to go into your storage and manually delete the directory if you made the same mistake i did to begin with
You are trying to write into a directory instead of file.
try this
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
File outputDir= new File(path);
outputDir.mkdirs();
File newFile = new File(path + File.separator + "test.png");
FileOutputStream out = new FileOutputStream(newFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Your code is correct, only little changes needs as follows,
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
// First Create Directory
File outputFile = new File(path);
outputFile.mkdirs();
// Now Create File
outputFile = new File(path,"testing.png");
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Also don't forget to give WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file.
If you are getting this error while working on Android Emulator; you need to enable SD Card storage on the emulator.
public static String SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/FolderName");
if(!myDir.exists())
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".png";
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 (Throwable e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
getExternalStoragePublicDirectory is now deprecated and you should use
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
Use this way :
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/mnt/sdcard/" + new Date().getTime() + ".jpg"));`
Path : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + file name
I am trying to record voice and save it in a file. For this I have to give a path to save the file, but I don't know how will I set the path...I have recently started working on android phone. In windows we set path like a drive e.g. C:/folder/folder....in android phone what will be my root? Where can I save an audio file? Write now I am working on emulator...Will the path be same for both emulator and phone?
we can create file like this in SD card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/folder");
myDir.mkdirs();
String fname = "file";
File file = new File (myDir, fname);
file is the path of file where you stored.
and add this Permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
_path=Environment.getExternalStorageDirectory().getPath() + "/RECORDS/";
// || ||
// VV VV
// storage path folder name
fileName = String.format("filename.mp3");
File file = new File(_path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Save your file in Sdcard.
File path = Environment.getExternalStorageDirectory();
String cardName = path.getName();
path=cardName+"/mypathname/file_name.mp3";
It is also possible in emulator. create sdcard , when you create emulator.
Thanks
Uri outputFileUri;
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new Filenter code here(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Is it possible to create a new folder for images (to be taken through my app) to be stored in, on the android phone? (Or SD Card as far as I'm concerned). I could name it what I like [Maybe the name of my app so the files are easily found] and then the images taken by launching the camera through my app will be stored there. I'm thinking it might have something to do with Uri's. (Just a guess.)
use this code
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" />
check this link Android saving file to external storage
Just use File operation for that..
File imageDirectory = new File("/sdcard/Images/"); // Path for location where you want to make directory, Internal or External storage
// have the object build the directory structure, if needed.
imageDirectory.mkdirs();
And in Application's manifest file put permission..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Why not?
String path = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/YourAppRootDir";
File dir = new File(path);
dir.mkdirs();