我试图将文件从服务器下载到外部SD卡。这是我的代码:
try {
URL url = new URL(address);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"myfile.txt");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 )
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress(downloadedSize, totalSize);
}
fileOutput.close();
问题是,该应用程序似乎无法找到外部SD卡位置:
03-20 13:03:29.615 16992-17244/com.example.myapp W/System.err: java.io.FileNotFoundException: /storage/emulated/0/myfile.txt: open failed: EACCES (Permission denied)
我需要添加一些新的权限吗?我添加了读写外部存储权限。有什么东西我不见了吗?非常感谢任何输入!
这是我的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>