2014-04-29 43 views
0

我一直在試圖將文件(音軌)從sdcard保存到內部存儲。 我已經與圖像與此代碼從sdacard保存音樂文件到內部存儲

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

這樣做現在這個效果很好,創建一個目錄,並保存我的位圖,但我想要做同樣的事情的音樂文件。
另外我想知道如何閱讀該文件(在應用程序中使用它)。
我已經使用這個代碼讀取位圖

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

附:代碼中,我已經盡力了,但似乎並沒有將生產權副本:

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

聽起來像你只需要找到在Java中執行文件複製操作(讀取緩衝區,寫入緩衝區,重複直到完成)的無數例子。 –

+0

嗯,我有點經歷了很多,並且我一直在輸入流中發現文件沒有發現異常,我只是教會了它有一種特殊的方式,因爲它是用於圖像的。 – Pavle37

+0

這意味着您的源代碼路徑錯誤。請注意,在最近的Android版本中,應用程序可能會在與ADB/DDMS等工具不同的路徑上看到外部存儲。 –

回答

1

這裏是爲我工作的代碼:

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

} 

希望它能幫助!