Android:将文件保存到 SD 卡?

标签 android file permissions download sd-card

我正在尝试创建一个程序,将 mp3 保存到 Android,可以通过 ASTRO 访问。我正在尝试将文件保存到/sdcard/media/audio。尽管该应用程序在 Logcat/DDMS 上没有出现任何错误,但找不到该文件。我添加了 WRITE_EXTERNAL_STORAGE 权限(连同 Internet 等)所以不是那样。

应用保存文件到sdcard有限制吗?

方法调用:

public void findSong(View view) throws Exception {
    edittext = (EditText) findViewById(R.id.edittext);          
    searchTerm = edittext.getText().toString();
    String address;         
    address = getMusic(searchTerm);         
    ImageManager img = new ImageManager(); //calls ImageManager (below)         
    img.DownloadFromUrl(address, title + ".mp3"); 
}

下载方法:

private final String PATH = "/data/data";  //put the downloaded file here

public void DownloadFromUrl(String imageURL, String fileName) {  
//this is the downloader method

try {
    URL url = new URL(imageURL); //you can write here any link
    File file = new File(fileName);
    long startTime = System.currentTimeMillis();
    Log.d("ImageManager", "download begining");
    Log.d("ImageManager", "download url:" + url);
    Log.d("ImageManager", "downloaded file name:" + fileName);

    /* Open a connection to that URL. */
    URLConnection ucon = url.openConnection();

    /* Define InputStreams to read from the URLConnection. */
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    /* Read bytes to the Buffer until there is nothing more to read(-1). */
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

   /* Convert the Bytes read to a String. */
   FileOutputStream fos = new FileOutputStream(PATH + file);
   fos.write(baf.toByteArray());
   fos.close();
   Log.d("ImageManager", "download ready in"
       + ((System.currentTimeMillis() - startTime) / 1000)
       + " sec");
   } catch (IOException e) {
       Log.d("ImageManager", "Error: " + e);
   }
}

感谢任何帮助。

最佳答案

如果文件是 mp3 你应该这样做:

Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

这将进行扫描并使其在媒体播放器中可用。

关于Android:将文件保存到 SD 卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4381968/

相关文章:

android - 如何 Root Android 模拟器?

android - 自定义 BaseAdapter EditText 单击并在按钮单击中更新数据库

java - Android 图片缓存

c# - 使用关联打开文件

python - 使用 multiprocessing.Pool 打开的文件太多

android - 如何使 ScrollView 中的项目位于屏幕中央

我可以同时写入两个不同的 FILE 指针吗?

permissions - 以编程方式关闭 "Inherit permissions from higher levels"

android - 来自适配器的 OnResquestPermissionResult

ubuntu - 如何使用wsl向ubuntu上的文件添加权限?