5 changed files with 162 additions and 5 deletions
-
4app/build.gradle
-
2app/src/main/AndroidManifest.xml
-
94app/src/main/java/com/iflytop/profilometer/api/record/RecordApi.java
-
12app/src/main/java/com/iflytop/profilometer/api/record/RecordRoutes.kt
-
55app/src/main/java/com/iflytop/profilometer/common/utils/FileUtil.java
@ -0,0 +1,55 @@ |
|||
package com.iflytop.profilometer.common.utils; |
|||
|
|||
import android.os.Environment; |
|||
|
|||
import java.io.File; |
|||
import java.io.FileOutputStream; |
|||
import java.io.IOException; |
|||
import java.nio.charset.StandardCharsets; |
|||
|
|||
public class FileUtil { |
|||
|
|||
/** |
|||
* 在 /storage/emulated/0/Download/<subDirName>/ 下创建子目录, |
|||
* 并在该目录中写入文本文件 |
|||
* |
|||
* ⚠️ 调用前请确保已经: |
|||
* 1) 在 AndroidManifest.xml 中声明了 WRITE_EXTERNAL_STORAGE 权限; |
|||
* 2) 已经在运行时向用户请求并获得了该权限; |
|||
* 3) 如果 targetSdkVersion ≥ 29,<application> 中开启了 requestLegacyExternalStorage="true"。 |
|||
* |
|||
* @param subDirName 子目录名称,例如 "MySubFolder" |
|||
* @param fileName 要写入的文件名,例如 "example.txt" |
|||
* @param content 文件内容 |
|||
* @throws IOException 外部存储不可用、目录创建失败或写入失败时抛出 |
|||
*/ |
|||
public static void writeTextToDownloadSubDir(String subDirName, |
|||
String fileName, |
|||
String content) throws IOException { |
|||
// 1. 确保外部存储已挂载 |
|||
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { |
|||
throw new IOException("External storage is not mounted"); |
|||
} |
|||
|
|||
// 2. 获取公共 Download 目录 |
|||
File downloadRoot = Environment.getExternalStoragePublicDirectory( |
|||
Environment.DIRECTORY_DOWNLOADS |
|||
); |
|||
if (downloadRoot == null) { |
|||
throw new IOException("Cannot access Download directory"); |
|||
} |
|||
|
|||
// 3. 在 Download 下创建子目录 |
|||
File targetDir = new File(downloadRoot, subDirName); |
|||
if (!targetDir.exists() && !targetDir.mkdirs()) { |
|||
throw new IOException("Failed to create sub-directory: " + targetDir.getAbsolutePath()); |
|||
} |
|||
|
|||
// 4. 在子目录中创建并写入文件 |
|||
File outFile = new File(targetDir, fileName); |
|||
try (FileOutputStream fos = new FileOutputStream(outFile)) { |
|||
fos.write(content.getBytes(StandardCharsets.UTF_8)); |
|||
fos.flush(); |
|||
} |
|||
} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue