andorid写文件问题
1.权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
2.动态申请权限
private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE" }; //然后通过一个函数来申请 public static void verifyStoragePermissions(Activity activity) { try { //检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } }
3.调用
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); verifyStoragePermissions(MainActivity.this); }
4.写文件函数
public static String readTxt(String txtPath) { File file = new File(txtPath); if(file.isFile() && file.exists()){ try { FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer sb = new StringBuffer(); String text = null; while((text = bufferedReader.readLine()) != null){ sb.append(text); } bufferedReader.close(); return sb.toString(); } catch (Exception e) { e.printStackTrace(); } } return null; } public static void writeTxt(String txtPath, String content) { FileOutputStream fileOutputStream = null; File file = new File(txtPath); try { if (! file.exists()) { //判断文件是否存在,如果不存在就新建一个txt file.createNewFile(); } fileOutputStream = new FileOutputStream(file); fileOutputStream.write(content.getBytes()); fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
5.使用
FileUtils_X.writeTxt(path, text);//写入唯一标识符
6.如果遇到权限问题,将这个按这个改低一点
android { compileSdkVersion 28 buildToolsVersion "29.0.2" defaultConfig { applicationId "chenlong.chenlong.createtoken" minSdkVersion 21 targetSdkVersion 28 versionCode 2 versionName "1.1" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" }
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>