i want to write on external sdcard (path: /mnt/external1/). i can read that path, but when i create a new folder on it pro grammatically it not create. i have already declare read write permission in manifeast.xml.
when i write code f.mkdir(); it return false;
and when i create an outputStream obj for that path and try to write something on that it through an exception Permission denied.
Note: My aim is to write something on external sdcrad which path is /mnt/external1 .
plz give me some solution .
my code is
public int createFolder(String FolderName)
{
File f = new File("/mnt/external1"+FolderName);
if(!f.exists())
{
if(f.mkdirs())
{
files= getFiles(path);
imageadapter.notifyDataSetChanged();
return 1;
}
}
}
public void createFolder(String FolderName)
{
File f = new File(new File("/mnt/external1"), FolderName);
if(!f.exists())
{
f.mkdirs();
}
}
This should work, but it is hardcoded for motorola xoom, tested.
Seems like this has been an issue for Xoom tablets (at least) since 3.2. Reference 18501 or 18559 on the Android bug list. You might have to rely solely on the path that getExternalStorageDirectory() returns for you.
try this way. this is the example not perfect code for your but you can get some idea/help
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
String path=Environment.getExternalStorageDirectory()+"myfolder";
boolean exists = (new File(path)).exists();
if(!exists) new File(path).mkdirs();
}
Use following code if it works
public int createFolder(String FolderName)
{
File f = new File(Enviornment.getExternalStorageDirectory(), FolderName);
if(!f.exists())
{
if(f.mkdirs())
{
files= getFiles(path);
imageadapter.notifyDataSetChanged();
return 1;
}
}
}
Related
I am using Android Studio with Java.
I have written a method (namely deleteWithExtension) to delete files from device internal memory. This method is adding some test files and tries to get the listof these files.
But the problem is that, the code never goes in the for-loop because of the array theFiles[] returns null. As you can see that, the code begins with sample files adding process so it should not be empty. I can also see those sample files in the Device File Explorer of Android Studio.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deleteWithExtension(Context mContext, String extension) {
//First let's add a few sample files with same extension.
CreateFile(mContext,"SampleFile1.smp","anything1");
CreateFile(mContext,"SampleFile2.smp","anything2");
CreateFile(mContext,"SampleFile3.smp","anything3");
CreateFile(mContext,"SampleFile4.smp","anything4");
CreateFile(mContext,"SampleFile5.smp","anything5");
//Now, 5 sample files have been added. Let get them and put in an array.
File dir = mContext.getFilesDir();
final String[] theFiles = dir.list();
for (final String file : theFiles) {
//do something here....
int aa=9;
//The code never goes into here, because array theFiles is always null but 5 sample files was added at first.
}
}
replace the CreateFile() method as follows. I hope I can help you.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + File.separator + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Both files are present on the sdcard, but for whatever reason exists() returns false the the png file.
//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";
File file2 = new File(path);
if (null != file2)
{
if(file2.exists())
{
LOG.x("file exist");
}
else
{
LOG.x("file does not exist");
}
}
Now, I've look at what's under the hood, what the method file.exists() does actually and this is what it does:
public boolean exists()
{
return doAccess(F_OK);
}
private boolean doAccess(int mode)
{
try
{
return Libcore.os.access(path, mode);
}
catch (ErrnoException errnoException)
{
return false;
}
}
May it be that the method finishes by throwing the exception and returning false?
If so,
how can I make this work
what other options to check if a file exists on the sdcard are available for use?
Thanks.
1 You need get the permission of device
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Get the external storage directory
File sdDir = Environment.getExternalStorageDirectory();
3 At last, check the file
File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
return false;
}
return true;
Note: filename is the path in the sdcard, not in root.
For example: you want find
/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
then filename is
./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
.
Please try this code. Hope it should helpful for you. I am using this code only. Its working fine for me to find the file is exists or not. Please try and let me know.
File file = new File(path);
if (!file.isFile()) {
Log.e("uploadFile", "Source File not exist :" + filePath);
}else{
Log.e("uploadFile","file exist");
}
Check that USB Storage is not connected to the PC. Since Android device is connected to the PC as storage the files are not available for the application and you get FALSE to File.Exists().
Check file exist in internal storage
Example : /storage/emulated/0/FOLDER_NAME/FILE_NAME.EXTENTION
check permission (write storage)
and check file exist or not
public static boolean isFilePresent(String fileName) {
return getFilePath(fileName).isFile();
}
get File from the file name
public static File getFilePath(String fileName){
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "FOLDER_NAME");
File filePath = new File(folder + "/" + fileName);
return filePath;
}
I want to ensure a byte array is being converted to a jpg correctly.
I've simplified the problem as follows:
public String saveToFile(String filename, String contents) {
String storageState = Environment.getExternalStorageState();
if(!storageState.equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("Media must be mounted");
}
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory, filename);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file, false);
fileWriter.write(contents);
fileWriter.close();
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Test
public void testDummyTest() throws Exception{
String out = saveToFile("preview-test.jpg", "preview-test.jpg");
}
This test passes and the path is something like file:///var/folders/z_/_syx1dpx7v9_pmktgdbx7f_m0000gn/T/android-external-cache8656399524188278404robolectric/ddf1c2ec-c0a8-44ce-90e4-7de2a384c57f/preview-test.jpg
However, I can't find this file my machine (yes, I've searched for it). I suspect this is a temp cache and its being cleared/deleted before I can view it.
Please can you tell me how to locate the "preview-test.jpg" file so I may open it in an image viewer, thus proving the image looks like it should. Thanks.
Note: the problem is not the jpg encoding, its simply getting direct access to the file.
I found a partial solution.
Rather than using the shadow environment to provide a path, I can instead use an absolute path for the machine. Eg root "/" would work.
So the code would look something like...
public String saveToFile(String filename, String contents) throws IOException {
File file = new File("/", filename);
FileWriter fileWriter;
fileWriter = new FileWriter(file, false);
fileWriter.write(contents);
fileWriter.close();
return file.getAbsolutePath();
}
#Test
public void testDummyTest() throws Exception {
String out = saveToFile("preview-test.jpg", "preview-test.jpg");
}
This then leaves a file on the root directory of the machine. :) Hope this helps somebody else out there.
i have a problem with my code that is supposed to write some data string to my sdcard. i use a class to do this:
public class CVS {
private String path;
private String filename;
private File dir;
private File file;
private FileWriter fw;
public CVS() {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/traffic/";
filename = "data.cvs";
file = new File(path, filename);
createDir();
}
private void createDir() {
dir = new File(path);
if(!dir.exists()) {
if(file.mkdirs() == false) {
Log.d(Config.LOGTAG, "UHOH!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
else Log.d(Config.LOGTAG, "dir exists");
}
public void writeToFile(String data) {
try {
fw = new FileWriter(file);
fw.append(data); Log.d(Config.LOGTAG, "data saved to file...");
}
catch(Exception e) {
Log.d(Config.LOGTAG, "file: " + e.getMessage());
}
}
}
this results ALWAYS in an exeption being caught in writeToFile(), saying "permission denied". actually, i set permissions to WRITE_EXTERNAL_STORAGE in the manifest. so - what am i doing wrong!?
additional info: real device with sd card mounted. no emulator. android 2.2. if i create the dir myself, the problem wont go away :(
Either:
Your manifest is wrong, or
Your external storage is mounted on your development machine, or
Your manual concatenation of your directory is wrong
Your code is ok but still you can add a check for whether sdcard is inserted or not, if you run this code and sdcard is not inserted then it will throw an exception, good practice is that you should always catch the exeptions.
you can check sdcard by following code...
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
{
//code or logic if sd card is inserted....
}
else
{
Log.e("Exception","SD Card not found!");
}
All of the answers are needed, but if it's a Samsung device, then you need to append "/external_sd/" to the path - because they decided they needed to dork with our minds and break the API:
"http://developer.samsung.com/forum/board/thread/view.do?boardName=GeneralB&messageId=162934&messageNumber=1381&startId=zzzzz~&searchType=TITLE&searchText=sdcard
I'm trying to save my file to the following location
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/" it works.
Now I'm assuming that I'm not able to create directory automatically this way.
Can someone suggest how to create a directory and sub-directory using code?
If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is what works for me.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in your manifest and the code below
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Actually I used part of #fiXedd asnwer and it worked for me:
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it Image2.PNG
File file = new File(extStorageDirectory, "Image2.PNG");
Make sure that you are using mkdirs() not mkdir() to create the complete path
With API 8 and greater, the location of the SD card has changed. #fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).
You can read more in the SDK documentation.
Make sure external storage is present:
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
private boolean isExternalStoragePresent() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)
.show();
}
return (mExternalStorageAvailable) && (mExternalStorageWriteable);
}
Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)
not allowed characters in file/folder names
" * / : < > ? \ |
U may find this code helpful in such a case.
The below code removes all ":" and replaces them with "-"
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();
this will create a folder named dor in your sdcard.
then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:
File file1 = new File(sdcard,"/dor/fitness.json");
.......
.....
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and don't forget to add code in manifest
This will make folder in sdcard with Folder name you provide.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name");
if (!file.exists()) {
file.mkdirs();
}
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
ivmage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`