2024-09-01
Android/Java
00

manifest.xml加权限:

python
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

oncreate加代码能向用户获取权限:

python
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); } //申请写权限 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } //申请创建文件 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.MANAGE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1); }

加一个方法:

python
public static void createFileRecursion(String fileName, Integer height) throws IOException { Path path = Paths.get(fileName); if (Files.exists(path)) { return; } if (Files.exists(path.getParent())) { if (height == 0) { Files.createFile(path); } else { Files.createDirectory(path); } } else { createFileRecursion(path.getParent().toString(), height + 1); createFileRecursion(fileName, height); } }

实现写入:

python
try { String jsonPath="/sdcard/Download/1.json"; createFileRecursion(jsonPath, 0); FileWriter fileWriter = new FileWriter(jsonPath); fileWriter.write(String.valueOf(msg.obj)); fileWriter.flush(); fileWriter.close(); Log.i("JSON_WRITE", "jsonPath: " + jsonPath); } catch (IOException e) { e.printStackTrace(); }
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!