I get my Image and video in Uri. I want to save that file in specific folder in internal memory. I tried Fileoutputstream and all but I can save it in camera folder but not specific folder. I want to save both image and video.
public void onClick(View view) {
if (string.contains("jpg")) {
String path = null;
try {
path = MediaStore.Images.Media.insertImage(getContentResolver(),
string, "img", null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Uri uri = Uri.parse(path);
Toast.makeText(getApplicationContext(), "Image saved", Toast.LENGTH_LONG).show();
saveImageandVideo(uri);
} else {
Uri uri = Uri.parse(string);
saveImage(uri);
Toast.makeText(getApplicationContext(), "Video saved", Toast.LENGTH_LONG).show();
}
}
});
my save code here
private void saveImageandVideo(Uri uri) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/folder_name");
if (!myDir.exists()) {
myDir.mkdirs();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
This code work but I can't able to save it in specific folder. It automatically saved it in camera folder(DCIM). and I can't able to save the videos. waiting for answers friends. Thanks in advance :D
Change your file variable creation as follows.
String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
File myDir = new File(root + "/folder_name");
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File(myDir,"filename.jpg/mp4");
//rest of your code
Change your saveImageandVideo() as
private void saveImageandVideo() {
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am currently making a journal app, so the users type their entry into an EditText and it saves in their phone and they can load it up later. At first I used just getFilesDir() but recently there is this weird rList file that shows up every time I open the app and I couldn't figure it out(I wrote a question about it). So now I want to save these files in this specific directory called TextEntries
Here is the code for my save funcction:
public void save(View v) {
textFile = inputTitle.getText().toString();
String text = inputFeelings.getText().toString();
FileOutputStream fos = null;
try {
String rootPath = getFilesDir().getAbsolutePath() + "/TextEntries/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
fos = openFileOutput(textFile, MODE_PRIVATE);
fos.write(text.getBytes());
inputFeelings.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/TextEntries/" + textFile,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
All help is welcome and thank you in advance.
replace
openFileOutput(textFile, MODE_PRIVATE);
with
new FileOutputStream(rootPath + textFile)
I would like to create a backup file in my memory card but all it does is return a file not found exception. I am specifying the path where the data should be saved. When i choose the Internal storage the file was saved but when i changed it to external storage, it returns me the file not found.
Here are the Screenshots:
enter image description here
final Preference prefStoragePath = findPreference("key_storage_path");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String pref_storage_path = settings.getString("set_storage_path",null);
startingDir = (pref_storage_path!=null)? pref_storage_path : Environment.getExternalStorageDirectory().toString();
Preference prefBackupManual = findPreference("key_backup_manual");
final String root = Environment.getExternalStorageDirectory().toString();
prefBackupManual.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
createBackupData(startingDir);
return false;
}
});
private void createBackupData(String dir){
String filename = "BackupData.txt";
String data = resultSet().toString();
try{
byte[] sha1hash;
File myFile = new File(dir,filename);
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
}finally {
Toast.makeText(getActivity(),"File saved in " + dir + "/" + filename ,Toast.LENGTH_SHORT).show();
}
}
what is happening?
you are trying to write data into a file that does not exist, thus a FileNotFoundException is thrown. The File(String, String) constructor does not create an actual file, you must take care of that by yourself.
How to fix it?
Check that your app has declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the Manifest. If you are targeting SDK 23 or above you should check and request that permission at runtime.
Your save method should look like:
private void createBackupData(String dir) {
String filename = "BackupData.txt";
String data = resultSet().toString();
FileOutputStream fos = null;
try {
byte[] sha1hash;
File myFile = new File(dir, filename);
//NOTE: your file will be overwritten in case it already exists
if (myFile.exists() || myFile.createNewFile()) {
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
Toast.makeText(getActivity(), "File saved in " + dir + File.separator + filename, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: a better approach is using Environment.getExternalStorageDirectory().getAbsolutePath() instead of Environment.getExternalStorageDirectory().toString()
I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.
I'm using this code to save images in the SD card (simulated or real) but all the testers of my app are telling me that the have a new folder in their Photos app with all my images (I don't know why on my Nexus 4 with KK this is not happening).
static public void storeImage(Bitmap image, String imgName) {
String root = Environment.getExternalStorageDirectory().toString();
File myRoot = new File(root + "/files");
if (!myRoot.exists()) {
myRoot.mkdir();
}
File myDir = new File(root + "/images/");
if (!myDir.exists()) {
myDir.mkdir();
}
File file = new File(BasePathToFile(imgName));
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to change de visibility, security or something to avoid that the Photos App or any App get access to my folder??
After reading a lot I have found this in the android dev page.
So at the end if you want that your files remain private you have to store them in the device.
So I have change my code to this:
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(context.getFilesDir(), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I hope this will be useful to someone.
Happy coding.
A #Sebastian pointed getExternalFilesDir(String type) is a more complete solution so i have changed de code to this:
private static Boolean SdMemoryExist() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
static public String BasePath(Context context) {
String _basePathToCheck;
if (SdMemoryExist()) {
_basePathToCheck = context.getExternalFilesDir(null).toString() + File.separator;
} else {
_basePathToCheck = context.getFilesDir().toString() + File.separator;
}
return _basePathToCheck;
}
static public void storeImage(Bitmap image, String imgName, Context context) {
File file = new File(BasePath(context), imgName);
if (file.exists()) {
if (file.delete()) {
createFile(image, file);
}
} else {
createFile(image, file);
}
}
static public void createFile(Bitmap image, File file) {
try {
if (file.createNewFile()) {
FileOutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding.
In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple code from the Google's examples:
try
{
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write((nameArticle+"|"+indexArticle).getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
But nothing happens: no exceptions, but I can see nothing in my FILE_NAME, besides the single record, which was added by me.
What am I doing wrong ? Is it possible at common to write to file in emulator ?
openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:
public Uri writeToExternalStoragePublic() {
final String filename = mToolbar.GetTitle() + ".html";
final String packageName = this.getPackageName();
final String folderpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
File folder = new File(folderpath);
File file = null;
FileOutputStream fOut = null;
try {
try {
if (folder != null) {
boolean exists = folder.exists();
if (!exists)
folder.mkdirs();
file = new File(folder.toString(), filename);
if (file != null) {
fOut = new FileOutputStream(file, false);
if (fOut != null) {
fOut.write(mCurrentReportHtml.getBytes());
}
}
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return Uri.fromFile(file);
} finally {
if (fOut != null) {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.
Have a Happy New Year.