I'm having problems with regards to creating a directory from an external storage, here is the method that I'm using.
public String createDir(String npath,String ndir,String file)
{
String[] paths = new String[] { npath, npath + ndir };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return "ERROR: Creation of directory " + path + " on sdcard failed";
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(npath + ndir + file)).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(ndir + file);
OutputStream out = new FileOutputStream(npath + ndir + file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + file);
return "Copied " + file;
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + file + e.toString());
return "Unable to copy " + file + e.toString();
}
}
else
return "Error!";
}
But I always get "ERROR: Creation of directory " + path + " on sdcard failed". Not to mention this is already installed in an android device. I tried looking for the directory of my application, but it is nowhere to be found, that supposedly, should be creating its folder automatically after the installation of my APK. Anyone who can resolve this?
Related
Now I copy mp4 file from external storage folder and save copy file in gallery with folder. But My gallery app doesn't have folder I code. Surely, File too. But In File Browser, There are exists correctly in DCIM folder.
So, How can I save file in gallery with folder that I code. Please let me know If you can solve this issue.
private void saveToGallery(String recVideoPath) {
progressdialog = new CNetProgressdialog(this);
progressdialog.show();
String folderName = "DuetStar";
String fromPath = recVideoPath;
String toPath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM;
File toPathDir = new File(toPath + "/" + folderName);
final File fromPathFile = new File(fromPath);
File toPathFile = new File(toPath + "/" + folderName, recVideoPath.substring(recVideoPath.lastIndexOf("/") + 1, recVideoPath.length()));
Log.d(TAG, "saveToGallery: " + RecordActivity.currentCreateFileName);
Log.d(TAG, "saveToGallery: " + toPathDir.toString());
Log.d(TAG, "saveToGallery: " + fromPath.toString());
Log.d(TAG, "saveToGallery: " + toPath.toString());
if (!toPathDir.exists()) {
toPathDir.mkdir();
} else {
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (toPathDir.exists()) {
fis = new FileInputStream(fromPathFile);
fos = new FileOutputStream(toPathFile);
byte[] byteArray = new byte[1024];
int readInt = 0;
while ((readInt = fis.read(byteArray)) > 0) {
fos.write(byteArray, 0, readInt);
}
Log.d(TAG, "saveToGallery: " + readInt);
fis.close();
fos.close();
Log.d(TAG, "saveToGallery: " + "Seucceful");
} else {
Toast.makeText(this, "There is no directory", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.getMessage();
}
progressdialog.dismiss();
}
You can save in specific folder as you wish see this code snippet for idea
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Video Folder name/";
//making the folder
new File(extStorageDirectory).mkdirs();
I am tring to create directory in External sdcard, I tested my code in MI (Android M), Samsung and in lenovo (Android L). Below code works fine in all devices except in lollipop.
private void crateDirectory() {
Log.d(TAG, "inside crateDirectory() ");
try {
String extPath = "";
String base = "/storage/sdcard1/"; //lenovo
// String base="/storage/9F44-E930/"; // for xiaomi
File baseFile = new File(base);
Log.d(TAG, "baseFile.exists() >>" + baseFile.exists()); // resulting TRUE
String path = "Android/data/package name/files/";
extPath = base + path;
Log.d(TAG, "exPath >>" + extPath);
File myFile = new File(Environment.DIRECTORY_DOWNLOADS + "/MY Download");
Log.d(TAG, "myFile >>" + myFile.getAbsolutePath());
File outputFile = new File(extPath, "" + myFile.getAbsolutePath());
if (!outputFile.exists()) {
Log.d(TAG, "Creating outputFile ....");
outputFile.mkdirs();
}
Log.d(TAG, "outputFile.exists() >>" + outputFile.exists() + "\n outputFile >>" + outputFile.getAbsolutePath());
} catch (Exception e) {
Log.d(TAG, "Exception >>" + Log.getStackTraceString(e));
}
Log.d(TAG, "end of crateDirectory() ");
}
when i am deleting the file the code is running and showing me the toast of deleted file also but not deleting it from SD card.
code is below :
delete_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
fn = baseAppDir.getPath()+ File.separator + folderName + File.separator
+ folderName + "_" + Integer.toString(imgNo) + ".jpg";
FileName = folderName + "_" + Integer.toString(imgNo)
+ ".jpg";
if (FileName!=null)
{
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}
}});
Have a look on following : Delete a file
Your can do like as below :
try {
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted", Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Try this may be its help full too..
File dir = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
Log.e(TAG, " get path ..**... " + dir.getPath());
Log.e(TAG, " get Directory ..**... " + dir.isDirectory());
Log.e(TAG, " get Name ..**... " + dir.getName());
Log.e(TAG, " get strign ..**... " + dir.list());
if (dir.isDirectory()) {
String[] children = dir.list();
Log.e(TAG, " children .... ... " + children.length);
for (int i = 0; i < children.length; i++) {
Log.e(TAG, "Delete old Image ...");
new File(dir, children[i]).delete();
}
}
this is code for delete multiple image from SD card.
replace
if (FileName!=null) {
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}
with
File file = new File(FileName);
if (file.delete()){
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}
I have 20k image files in a folder inside my local storage, I need to display the image by its file name from local storage. How to do it? I attached my code here:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "jpg", getContext().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
final Bitmap bit = BitmapFactory.decodeStream(MyFile);
imageView.setImageBitmap(bit);
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
File f = new File(filePath);
if(f.exits()){
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(bm);
}else{
// invalid path
}
}
}
Update Section:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
// this never be true see below image
}
You have to do like this
File file = new File(Environment.getExternalStorageState()+"/Android/obb/convertMp3ToDb/ldoce6pics/"+fileName);
if (file.exists()) {
// your condition should ne likr this.
}
I am working on an Android version 2.3.3 application which depends on SMS for SMS dealing. I have written two classes SendSMS and ReceiveSMS. I want to create a log file which logs each SMS that it is sent or received. For creating log file I have written code but does not work.
Following is my code,
public void WriteOnLog()
{
File exportDir = Environment.getExternalStorageDirectory();
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" msg";
}
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
txt = dt + " |" +" Send " + "| " + phoneNumber + " | " + message.toUpperCase();
out.write(txt + "\n");
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
I have used the OutputStreamWriter (instead of FileWriter) Approach. I have it working in my dev environment and tested on device (android 2.3.6). try this out:
try {
File directory;
if(isSDCard){
directory = new File(Environment.getExternalStorageDirectory().toString()+"/"+folderNameOrPath+"/");
}
else{
directory = new File(folderNameOrPath);
}
boolean fileReturnVal = directory.mkdirs();
if(fileReturnVal){
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder Created successfully");
}
else{
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder either already exists or creation failed");
}
File file = new File(directory, fileNameWithExtention);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//Write the string to the file
osw.write(text);
osw.flush();
osw.close();
//file saved
Toast.makeText(context, "Text saved in SD Card", Toast.LENGTH_SHORT).show();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: File Not Found ERROR: " + e.toString());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: IOException ERROR: " + e.toString());
return false;
} catch (Exception e) {
Log.e("Storage", "Write in SD Card: ERROR: " + e.toString());
return false;
}
you can set append mode for you task. The variables isSDCard, folderName, fileNameWithExtn. etc. are method level variables. I am passing those as parameters.