Rectangle 27 15

@palash k answer is correct and worked for internal storage files, but in my case I want to open files from external storage also, my app crashed when open file from external storage like sdcard and usb, but I manage to solve the issue by modifying provider_paths.xml from the accepted answer

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">

<external-path path="Android/data/${applicationId}/" name="files_root" />

<root-path
    name="root"
    path="/" />

</paths>

and in java class(No change as the accepted answer just a small edit)

Uri uri=FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID+".provider", File)

This help me to fix the crash for files from external storages, Hope this will help some one having same issue as mine :)

<root-path
<external-path path="Android/data/${applicationId}/" name="files_root" />

i find this from various search results, let me check again and get back to u asap

also the external storage you mention is sd card or inbuilt storage?

Android/data/${applicationId}/

android.os.FileUriExposedException: file:///storage/emulated/0/test.tx...

android android-file android-7.0-nougat
Rectangle 27 15

@palash k answer is correct and worked for internal storage files, but in my case I want to open files from external storage also, my app crashed when open file from external storage like sdcard and usb, but I manage to solve the issue by modifying provider_paths.xml from the accepted answer

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">

<external-path path="Android/data/${applicationId}/" name="files_root" />

<root-path
    name="root"
    path="/" />

</paths>

and in java class(No change as the accepted answer just a small edit)

Uri uri=FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID+".provider", File)

This help me to fix the crash for files from external storages, Hope this will help some one having same issue as mine :)

<root-path
<external-path path="Android/data/${applicationId}/" name="files_root" />

i find this from various search results, let me check again and get back to u asap

also the external storage you mention is sd card or inbuilt storage?

Android/data/${applicationId}/

android.os.FileUriExposedException: file:///storage/emulated/0/test.tx...

android android-file android-7.0-nougat
Rectangle 27 6

Android has a special security feature: the /mnt/sdcard filesystem is execution-protected. You cannot run an executable that is located on the external storage (a.k.a. USB storage). If you want to run ffmpeg binary on your device, you must load it into one of the internal directories. For example, you can pack it into libs/armeabi of your Java project, so that the installer will automatically unpack it into the /data/data/<your package>/lib directory on the device. Or you can find another directory, like /data/local, where you can put the executable binary file with adb push

Thanks,I put it in the root and it worked!

same issue!! I am merging two videos which are at internal storage and storing the resulting video on the same location but it gives this-java.io.IOException: No such file or directory

@AkashDubey: to check if this is the same issue, run ffmpeg with no file parameters, e.g. fffmpeg -?. If you still get same java exception, it's it. If not, your problem is different, and has to do with the way you specify input or output file paths. In the latter case, feel free to open a separate question and disclose more details on how you attempt to run ffmpeg from your app.

@AlexCohn don't worry, I wasn't asking i was just telling that I was executing ffmpeg command before loading ffmpeg, that was the issue and now it is resolved

Problems with ffmpeg command line on android - Stack Overflow

android ffmpeg
Rectangle 27 0

The example video is for desktop java, where you can normally write files without specifying a path. However on Android you should always specify one - you can use internal storage or external storage. Here's the Android guide on how to write files to internal storage: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

java - Object is not writing to file triggering FileNotFoundException ...

java android file-io java-io filenotfoundexception
Rectangle 27 0

To copy files from internal memory to SD card and vice-versa using following piece of code:

public static void copyFile(File src, File dst) throws IOException
{
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try
    {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    }
    finally
    {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

Make sure you have the following permissions if writing/reading external memory <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Don't you have to close the results from new FileInputStream(src) and new FileOutputStream(dst) which don't even have a reference here?

Nope, closing of channel closes those streams

@barmaley: What about folder?? Instead of file. I have 3 folders and i want to cut-paste it to new location. But it shows an error at line FileChannel inChannel = new FileInputStream(src).getChannel(); saying filenotfound exception. though file exists. :( Any solution to this?

java - How to move/rename file from internal app storage to external s...

java android file
Rectangle 27 0

For Move file best way is Renaming it's path with different path and name example:

File from = new File(Environment.getExternalStorage().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorage().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);

java - How to move/rename file from internal app storage to external s...

java android file
Rectangle 27 0

An alternative to the copying using your own function is to use Apache's library's class "FileUtils" , in the function called copyFile :

FileUtils.copyFile(src, dst, true);

java - How to move/rename file from internal app storage to external s...

java android file
Rectangle 27 0

Internal and external memory is two different file systems. Therefore renameTo() fails.

You will have to copy the file and delete the original

java - How to move/rename file from internal app storage to external s...

java android file
Rectangle 27 0

See below one to get file from android Assets and copy it to the specific sdcard location.

I will first check for the pdf file whether it is already available at desire path or not.

File file1 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_Molding.pdf");
    File file2 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_PK.pdf");
    File file3 = new File("/sdcard/SampleProjectApp/Alone.mp4");

    if(!((file1.exists())) || !((file2.exists())) || !((file3.exists()))) {
        ArrayList<String> files = new ArrayList<String>();
        files.add("WindsorONE_Mobile_Molding.pdf");         
        files.add("WindsorONE_Mobile_PK.pdf"); 
        files.add("Alone.mp4");
        new myAsyncTask().execute(files);
    }

Now, if the file is not present at that position then it will execute the myAsyncTask to copy file from assets to the SdCard.

// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {         
    ArrayList<String> files;         
    ProgressDialog dialog;         
    @Override         
    protected void onPreExecute() {             
        dialog = ProgressDialog.show(ListSample.this, "W1 SALES (beta)", "Loading...");         
    }         
    @Override         
    protected Void doInBackground(ArrayList<String>... params) {              
        files = params[0];             
        for (int i = 0; i < files.size(); i++) {                 
            copyFileFromAssetsToSDCard(files.get(i));                
        }             return null;         
    }         
    @Override         
    protected void onPostExecute(Void result) {             
        dialog.dismiss();         
    }      
} 



 // Function to copy file from Assets to the SDCard
public void copyFileFromAssetsToSDCard(String fileFromAssets){
    AssetManager is = this.getAssets();
    InputStream fis;
    try {

        fis = is.open(fileFromAssets);
        FileOutputStream fos;
        if (!APP_FILE_PATH.exists()) {
            APP_FILE_PATH.mkdirs();
        }
        fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/SampleProjectApp", fileFromAssets));
        byte[] b = new byte[8];
        int i;
        while ((i = fis.read(b)) != -1) {
            fos.write(b, 0, i);
        }
        fos.flush();
        fos.close();
        fis.close();
    } 
    catch (IOException e1) {
        e1.printStackTrace();
    }
}

with

Below code is copy file from one path to another path. You simply have to pass the path of the file where it is exist and the path where it has to be copy.

public static boolean copyFile(String from, String to) {
try {
    int bytesum = 0;
    int byteread = 0;
    File oldfile = new File(from);
    if (oldfile.exists()) {
        InputStream inStream = new FileInputStream(from);
        FileOutputStream fs = new FileOutputStream(to);
        byte[] buffer = new byte[1444];
        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
        }
        inStream.close();
        fs.close();
    }
    return true;
} catch (Exception e) {
    return false;
}

Im trying to store the pdf file in sdcard/Android/data/com.project.projectname/cache im trying to store it in cache.

I have a question for the copyFileFromAssetsToSDCard function as i'm new to android. Is the AssetManager getting the files from your app's package res/raw or android Internal storage data/data/com.myproject.projectname/files/ Im having a FileNotFoundException:myfile.pdf for this method

@GerjoBronosa: My friend you have to put the file in assets folder. AssetManager will not get file from the res/raw.

OK. but my problem is about copying files saved in the internal storage(data/data/com.example.project/files/file.pdf) not writing files from my assets or raw.

java - Copy Files from Internal Storage to external storage - Stack Ov...

java android android-intent
Rectangle 27 0

you can use this method

boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent)
{
    InputStream in = null;
    OutputStream out = null;
      in = //Place your file in the inputstream
      out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + filename);
      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;
}
else
{
Toast.makeText(getApplicationContext(), "SD Card not present", Toast.LENGTH_LONG).show();
}

thanks for the quick reply. I'm getting a FileNotFoundException (Read-only file system). I'll add my codes on how i write the files in the internal storage too..

where are you getting it

Im getting the file from the internal storage data/data/packagename/files/myfile.pdf

InputStream in = new FileInputStream(Environment.getDataDirectory()+"/files/myfile.pdf")

Im still getting a FileNotFoundException but now its No such File or directory. I dont think this is the way to access the internal directory Environment.getDataDirectory()

java - Copy Files from Internal Storage to external storage - Stack Ov...

java android android-intent
Rectangle 27 0

SharedPreferences preferences=this.getSharedPreferences("com.example.application", Context.MODE_PRIVATE);
Map<String,?> keys = preferences.getAll();
Properties properties = new Properties();
for(Map.Entry<String,?> entry : keys.entrySet()){
    String key = entry.getKey();
    String value = entry.getValue().toString();
    properties.setProperty(key, value);      
}
try {
    File file = new File("externalPreferences.xml");
    FileOutputStream fileOut = new FileOutputStream(file);
    properties.storeToXML(fileOut, "External Preferences");
    fileOut.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    File file = new File("externalPreferences.xml");
    FileInputStream fileInput = new FileInputStream(file);
    Properties properties = new Properties();
    properties.loadFromXML(fileInput);
    fileInput.close();

    Enumeration enuKeys = properties.keys();
    SharedPreferences.Editor editor = preferences.edit();
    while (enuKeys.hasMoreElements()) {
        String key = (String) enuKeys.nextElement();
        String value = properties.getProperty(key);
        editor.putString(key, value);
        editor.commit();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

NOTE You can handle only String type preferences with this code,

It works, but now I'll have to redesign other parts of code parsing to integer type, because everything is a string.

java - How to transfer sharedpreferences file from internal storage to...

java android xml file sharedpreferences
Rectangle 27 0

public boolean copyFile(File src, File dst) {
    boolean returnValue = true;

   FileChannel inChannel = null, outChannel = null;

    try {

        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(dst).getChannel();

   } catch (FileNotFoundException fnfe) {

        Log.d(logtag, "inChannel/outChannel FileNotFoundException");
        fnfe.printStackTrace();
        return false;
   }

   try {
       inChannel.transferTo(0, inChannel.size(), outChannel);

   } catch (IllegalArgumentException iae) {

         Log.d(logtag, "TransferTo IllegalArgumentException");
         iae.printStackTrace();
         returnValue = false;

   } catch (NonReadableChannelException nrce) {

         Log.d(logtag, "TransferTo NonReadableChannelException");
         nrce.printStackTrace();
         returnValue = false;

   } catch (NonWritableChannelException nwce) {

        Log.d(logtag, "TransferTo NonWritableChannelException");
        nwce.printStackTrace();
        returnValue = false;

   } catch (ClosedByInterruptException cie) {

        Log.d(logtag, "TransferTo ClosedByInterruptException");
        cie.printStackTrace();
        returnValue = false;

   } catch (AsynchronousCloseException ace) {

        Log.d(logtag, "TransferTo AsynchronousCloseException");
        ace.printStackTrace();
        returnValue = false;

   } catch (ClosedChannelException cce) {

        Log.d(logtag, "TransferTo ClosedChannelException");
        cce.printStackTrace(); 
        returnValue = false;

    } catch (IOException ioe) {

        Log.d(logtag, "TransferTo IOException");
        ioe.printStackTrace();
        returnValue = false;


    } finally {

         if (inChannel != null)

            try {

               inChannel.close();
           } catch (IOException e) {
               e.printStackTrace();
           }

        if (outChannel != null)
            try {
                outChannel.close();
           } catch (IOException e) {
                e.printStackTrace();
           }

        }

       return returnValue;
    }

Do you have any reasons or commentary for the changes? Why is this an improvement?

java - How to move/rename file from internal app storage to external s...

java android file
Rectangle 27 0

Android has a special security feature: the /mnt/sdcard filesystem is execution-protected. You cannot run an executable that is located on the external storage (a.k.a. USB storage). If you want to run ffmpeg binary on your device, you must load it into one of the internal directories. For example, you can pack it into libs/armeabi of your Java project, so that the installer will automatically unpack it into the /data/data//lib directory on the device. Or you can find another directory, like /data/local, where you can put the executable binary file with adb push

Thanks,I put it in the root and it worked!

Problems with ffmpeg command line on android - Stack Overflow

android ffmpeg
Rectangle 27 0

FileChannel to copy files in internal storage of the app would be MODE_PRIVATE.

Welcome to Stack Overflow! This appears to be more of a question than an answer, if you want to ask a question please create a new question. (Also this is over a year old and already answered.)

java - How to move/rename file from internal app storage to external s...

java android file