想列出android 内部存储根目录(内部存储也是sd卡形式)
File path = Environment.getExternalStorageDirectory(); File[] files=path.listFiles(); for(int i=0;i<files.length;i++){ str1 += files[i].getAbsolutePath()+","; } textView.setText("bb"+str1);
发现老是提示报错 ,debug 发现eacces,是权限问题
1、先在AndroidManifest.xml 里
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
还加了
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
发现还没有用,即使在手机权限里加上还不行
2、加上下面代码好了,新版本需要用下面的方式
private final int REQUEST_EXTERNAL_STORAGE = 1; private String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; public void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don‘t have permission so prompt the user ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } }
然后在
onCreate 里调用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
verifyStoragePermissions(this);
3、后面处理读写文件也ok了
try { File urlFile = new File(str3+"/sd/test.txt"); Log.e("-----------","111"); InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile), "UTF-8"); BufferedReader br = new BufferedReader(isr); Log.e("-----------","112221"); String str = ""; String mimeTypeLine = null ; while ((mimeTypeLine = br.readLine()) != null) { str = str+mimeTypeLine; } Log.e("-----------",str); textView.setText(str); } catch (Exception e) { e.printStackTrace(); }
原文:https://www.cnblogs.com/cnchengv/p/14664560.html