How to find external storage directory - android

static final String FILE_LOG = "log.txt";
private void SaveLogToExternalStorage()
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos = null;
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file);
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
String savedFile = Environment.getExternalStorageDirectory() + "/" + FILE_LOG;
Toast.makeText(this, "Log is saved to " + savedFile, Toast.LENGTH_SHORT).show();
}
This function prints Log is saved to mnt/sdcard/log.txt Actually the file is saved to mnt/sdcard/Android/data/package.name/files/log.txt How can I find this directory programmatically to show correct message?

Solved by using file.getAbsolutePath()

Just change following line.
String savedFile1 = Environment.getExternalStorageDirectory() + getFileStreamPath(FILE_LOG).toString();
Toast.makeText(this, "Log is saved to " + savedFile1, Toast.LENGTH_LONG).show();
Log.d("File", savedFile1);
This will gives output like: /mnt/sdcard/data/data/com.android.experimentalproject/files/log.txt
And as per Alex Farber..
String savedFile = file.getAbsolutePath().toString();
Toast.makeText(this, "Log is saved to " + savedFile, Toast.LENGTH_SHORT).show();
Log.e("PATH", savedFile1);
Output: /mnt/sdcard/Android/data/com.android.experimentalproject/files/log.txt
He is spot on...
Hope this will help you.
Thanks..

Related

How to create folder in gallery and save file

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

Error while deleting a file from SD card

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

Add res/raw folder content file (video) to external SD folder

The idea is I want to put the content/s of my res/raw folder to external sd folder named "myFolder".
my way is that I used Uri to access the video file in res/raw and used FileOutputStream and its not working, Is my way possible?
*I already have the permissions needed to READ and WRITE to external sd, and it is placed correclty in manifest.
CODE IS BELOW, THANK YOU
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/myFolder/";
Uri UriPath=Uri.parse
("android.resource://com.example.videoplayer.videoplayer/" + R.raw.video1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videoplayer);
File videodir= new File(basepath);
if (!videodir.exists()) {
videodir.mkdirs();
Toast.makeText(getApplicationContext(),
"Directory created!", Toast.LENGTH_LONG)
.show();
}else{
Toast.makeText(getApplicationContext(),
"Directory exists!", Toast.LENGTH_LONG)
.show();
}
File file = new File (basepath, "android.resource://com.example.videoplayer.videoplayer/" + R.raw.video1); //Im not sure if the code reaches the video1 file
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file); //this line doesnt work
Toast.makeText(getApplicationContext(),
"File created!", Toast.LENGTH_LONG)
.show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"File error!", Toast.LENGTH_LONG)
.show();
}
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
To use above code call function with copyFileOrDir("myFolder");

how to use BitmapFactory.decodeFile() to get the Bitmap

i am trying to download image from internet in original quality. then trying to BitmapFactory.decodeFile() to get the Bitmap
to perform this task i tried this but i am getting this error:
The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments (FileOutputStream)
code:
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname);
myDir.mkdirs();
String str = currentUrl.substring(currentUrl.lastIndexOf('/') + 1,
currentUrl.length());
String fname = "Wallpaper-" + str + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap = BitmapFactory.decodeFile(out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
You should pass the file name to the function BitmapFactory.decodeFile()instead of the output stream

Create log file on SendSms and Receive SMS

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.

Categories

Resources