2

我开发了一个应用程序,用户可以在其中从服务器下载 .mp3 文件。并预定义了 mnt/sdcard/foldername 的路径以保存此类文件。我已经在 HTC、LG、三星运行了我的程序,但是当我在三星 Galaxy s2 运行相同的程序时,遇到了一个无法在 mnt/sdcard/foldername 中写入(存储)的问题并尝试了

 Environment.getExternalStorageDirectory().getAbsolutePath()

但它显示给定路径中下载的文件名和每个文件属性的零字节。有什么想法可以解决这个问题吗?

4

3 回答 3

1

SG2 通常没有 sd 卡,而是使用内部闪存作为“外部”存储。我已经用这段代码解决了这个问题:

    private File initCacheDir() {
        String sdState = android.os.Environment.getExternalStorageState();
            File imageCacheDir;
            if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
                File sdDir = android.os.Environment.getExternalStorageDirectory();      
                imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
            }
            else
                imageCacheDir = context.getCacheDir();

            if(!imageCacheDir.exists())
                 imageCacheDir.mkdirs();        
            return imageCacheDir;
}

请注意,此代码为您提供了缓存目录的位置,该目录通常位于 sd 卡上的 Android/data 文件夹中。

您将在此处找到如何使用 SG2 解决此问题的更多详细信息: 如何在三星和所有其他设备上获得正确的外部存储?

于 2012-08-23T11:42:07.187 回答
1

试试这个

 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
于 2012-08-23T12:09:20.723 回答
1

我终于找到了代码

public void download(String urlToDownload){

URLConnection urlConnection = null;

try{

    URL url = new URL(urlToDownload);

    //Opening connection of currrent url

    urlConnection = url.openConnection();
    urlConnection.connect();

    //int lenghtOfFile = urlConnection.getContentLength();


String PATH = Environment.getExternalStorageDirectory() + "/1/";

File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = url.openStream();


byte[] buffer = new byte[1024];

int len1 = 0;

while ((len1 = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len1);
}

fos.close();
is.close();

System.out.println("downloaded"+urlToDownload);

}catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();

}

}

来源:链接

于 2012-09-17T10:53:40.923 回答