0

I have File Song (which is a song.mp3 from other activity) i want to save it in internal storage in specific folder.

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_playlist);

        Bundle bundle = getIntent().getExtras();
        File song = (File)bundle.get("playlist");


    }
  • possible duplicate https://stackoverflow.com/questions/31094071/copy-file-from-the-internal-to-the-external-storage-in-android – Xay Aug 12 '19 at 05:37
  • Similar post: https://stackoverflow.com/questions/4178168/how-to-programmatically-move-copy-and-delete-files-and-directories-on-sd – KIRAN CSN Aug 12 '19 at 05:45
  • it did'nt help me i got unhandled exception: java.io.IOException , i pass src file as my song file and destination file with path String dstPath = Environment.getExternalStorageDirectory() + File.separator + "myApp" + File.separator; File dst= new File(dstPath); moveFile(songfile,dst); – Sukhchain Kharoud Aug 12 '19 at 07:22

1 Answers1

1

First of all you need to wrap everything in try/catch and log the exception block to figure out what error is with help of exception.getMessage()

Than the example of copying file is the following

 InputStream inStream = null;
    OutputStream outStream = null;

    try{

        File afile =new File("C:\\foldeOne\\Afile.txt");
        File bfile =new File("C:\\foldeTwo\\Afile.txt");

        inStream = new FileInputStream(afile);
        outStream = new FileOutputStream(bfile);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes
        while ((length = inStream.read(buffer)) > 0){

            outStream.write(buffer, 0, length);

        }

        inStream.close();
        outStream.close();

        //delete the original file
        afile.delete();

        System.out.println("File is copied successful!");

    }catch(IOException e){
        //Here you suppose to handle exception to figure out what went wrong
        e.printStackTrace();
    }
}

original was here https://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/

Bo Z
  • 2,359
  • 1
  • 13
  • 31