Question

I have been trying to save the file ( soundtrack ) from sdcard to the internal storage. I have already done so with the image with this code

ContextWrapper cw = new ContextWrapper(getApplicationContext());
     // path to /data/data/fairyTale/app_data/ImgMsc
    File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath=new File(directory,Name+".png");

    FileOutputStream fos = null;
    try {           

        fos = new FileOutputStream(mypath);

   // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

Now this works well, creates a directory and saves my bitmap, but i want to do the same thing for the music file.
Also i want to know how to read that file ( use it in the app ).
I have used this code to read the bitmap

File f=new File(path,name+".png");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        return b;

P.S. the code i have tried, but doesn't seem to be producing the right copy:

String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
    File music = new File(filePath);
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/fairyTale/app_data/ImgMsc
    File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
    File mypath=new File(directory,name+".mp3");
    try {
    InputStream is=new FileInputStream(music);
    OutputStream os;
    os = new FileOutputStream(mypath);
    byte[] buff=new byte[1024];
        int len;
        while((len=is.read(buff))>0){
            os.write(buff,0,len);
        }
        is.close();
        os.close();
    }
Was it helpful?

Solution

Here is the code that worked for me:

private void saveToInternalStorage(String name){
    String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
    File music = new File(filePath);
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to your data
    File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
    File mypath=new File(directory,name+".mp3");
    // Create imageDir
    try {
    InputStream is=new FileInputStream(music);
    OutputStream os;
    os = new FileOutputStream(mypath);
    byte[] buff=new byte[1024];
        int len;
        while((len=is.read(buff))>0){
            os.write(buff,0,len);
        }
        is.close();
        os.close();
    DeleteFile(filePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top