我开发了一个应用程序,用户可以从服务器下载.mp3文件。并预定义了mnt / sdcard / foldername的路径来保存这些文件。我在HTC运行我的程序,LG,三星的工作非常完美,但是当我在三星galaxy s2运行同一个程序时遇到一个无法在mnt / sdcard / foldername中编写(存储)的问题并尝试了
Environment.getExternalStorageDirectory().getAbsolutePath()
但它显示了在给定路径中下载的文件名和每个文件属性的零字节。有什么想法解决这个问题吗?
答案 0 :(得分: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解决此问题的更多详细信息: How could i get the correct external storage on Samsung and all other devices?
答案 1 :(得分: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();
答案 2 :(得分: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();
}
}
来源:link