我的应用有问题。我正在尝试从SD卡读取文件,但我找不到任何文件。文件被添加到我的SD卡中的主文件夹中。我也试过创建一个新文件夹并从文件夹中读取文件,但我遇到了同样的问题。来自SD卡的其他文件(不是我为应用程序添加的)也不可见。我在真实设备三星Galaxy A3上测试我的应用程序。你有什么想法,问题在哪里,或者我做错了什么?以下是我的代码:
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RecipeActivity"></activity>
</application>
活动类:
File dir = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "receip.txt");
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
Log.d("File text:", text.toString() );
Toast.makeText(getApplicationContext(),"File Found", Toast.LENGTH_SHORT);
}
else
{
Log.d("Romek file:", "File not found" );
Toast.makeText(getApplicationContext(),"File not Found", Toast.LENGTH_SHORT);
}
我还在下面添加了方法来检查我的SD卡是否可写和可读。所有方法都返回true。
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d("Romek", "External Storage is writable");
return true;
}
Log.d("Romek", "External Storage is not writable");
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Log.d("Romek", "External Storage is readable");
return true;
}
Log.d("Romek", "External Storage is not readable");
return false;
}
我使用了运行时权限,我可以读取文件,但是我还有其他问题。如何在外部SDCARD中获取正确的文件路径。当我使用Environment.getExternalStorageDirectory()。getAbsolutePath()时,我在手机中恢复了外部卡的路径,而不是SDCARD。
答案 0 :(得分:0)
如果您的手机有Android 6.0或更新版本,则必须询问运行时权限。您可以从https://developer.android.com/training/permissions/requesting.html
获取更多信息